I've been getting headaches trying to implement a recursive mergesort but I keep getting problem after problem.
Right now, I have a lot of trouble when adding elements which has caused 75% of my problems earlier.
This is the code of the implementation, the main problem is the merge part:
static public void DoMerge(LinkedList <Contacto> L, int left, int mid, int right)
{
LinkedList <Contacto> temp = new LinkedList <Contacto>();
int i, left_end, num_elements, tmp_pos, comp;
left_end = (mid - 1);
tmp_pos = left;
num_elements = (right - left + 1);
while ((left <= left_end) && (mid <= right))
{
comp= L.get(left).get_name().compareTo(L.get(mid).get_name());
if (comp<=0)
temp.add(tmp_pos++,L.get(left++));
else
temp.add(tmp_pos++,L.get(mid++));
}
while (left <= left_end)
temp.add(tmp_pos++,L.get(left++));
while (mid <= right)
temp.add(tmp_pos++,L.get(mid++));
for (i = 0; i < num_elements; i++)
{
L.set(right, temp.get(right));
right--;
}
}static public void MergeSort_Recursive(LinkedList <Contacto> L, int left, int right)
{
int mid;
if (right > left)
{
mid = (right + left) / 2;
MergeSort_Recursive(L, left, mid);
MergeSort_Recursive(L, (mid + 1), right);
DoMerge(L, left, (mid+1), right);
}
}
The main problem again is the merge part which is constantly troubling me, specially adding the elements to the temporary list. The compiler throws me an out of bounds exception.
The problem is
LinkedList <Contacto> temp = new LinkedList <Contacto>();
You initialized an empty list. But, this line:
temp.add(tmp_pos++,L.get(left++));
You insert an Object to index tmp_pos which can be larger than the current size of temp (first, size of temp is zero). (Read more about add.)
You can fix this by understanding that, for merge sort, temp actually is used as a stack, so this part is not necessary temp.add(tmp_pos++,L.get(left++));, use temp.add(L.get(left++)); instead. (Replace other statements in similar manner).
And for the last part, just use
for (i = 0; i < num_elements; i++)
{
L.set(right, temp.removeLast());
right--;
}
Related
try {
for (i = 0; i < data.length; i++) {
working[i] = data[i];
}
FileWriter fw3 = new FileWriter("quicksort.dat");
long startTime3 = System.nanoTime();
quickSort(working,0, working.length - 1);
long endTime3 = System.nanoTime();
long totalTime3 = endTime3 - startTime3;
System.out.println("The time to complete the quick sort was :" + totalTime3 + " nano seconds");
for (i = 0; i < working.length; i++) {
fw3.write(Integer.toString(working[i]) + "\n");
}
System.out.println("The file has been sorted by quick sort and output to quicksort.dat \n");
fw3.close();
} catch (IOException e) {
System.out.println(e);
}
static void quickSort(int data[], int left, int right) {
int i, j;
int partition;
if (right > left) {
partition = data[right];
i = left - 1;
j = right;
for (;;) {
while (data[++i] < partition);
while (data[--j] > partition);
if (i >= j) {
break;
}
swap(data[i], data[j]);
swap(data[i], data[right]);
quickSort(data, left, i - 1);
quickSort(data, i + 1, right);
}
}
}
static void swap(int left, int right) {
int array[] = new int[19];
int temp = array[left];
array[left] = array[right];
array[right]=temp;
This is just snippets of the code whole program is other sorts. I get an out bounds error every time it gets down to the quicksort function. I use 19 as my array because that is how big the file is I have tried 20 to see if it fixes it with no luck.
EDIT: I provided updated code down below to reflect changes that were made I still get an out of bounds error.
static void quickSort(int data[], int left, int right) {
int i, j;
int partition;
if (right > left) {
partition = data[right];
i = left - 1;
j = right;
for (;;) {
while (data[++i] < partition);
while (data[--j] > partition);
if (i >= j) {
break;
}
swap(data, i, j);
swap(data, i, right);
quickSort(data, left, i - 1);
quickSort(data, i + 1, right);
}
}
}
static void swap(int array[], int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
You have declared swap as :
void swap(int left, int right)
So the arguments are the indexes into the array.
However, you call it with :
swap(data[i], data[j]);
So you are passing the VALUES in the array.
Try changing the call to :
swap(i, j);
EDIT TO ADD:
It must be pointed out that the issue above is just ONE issue with the sorting algorithm presented. Another problem is that the swap algorithm does not actually swap anything. It creates a local array variable array, operates on that and then returns (so discarding that local variable).
If your assignment is to output a sorted list of numbers, and that the numbers must be sorted using the sorting code presented - then that assignment is impossible because the sorting code presented is hopelessly flawed as a sorting algorithm; it does NOT sort (as you have found yourself), and has blatant severe issues compared to a correct implementation of quicksort (eg, you can compare to the answer here : https://stackoverflow.com/a/63811974/681444 )
EDIT TO ADD FOLLOWING REVISED CODE:
The revised sorting code is STILL hopelessly busted. It is not a correct implementation of QuickSort, and still does not sort correctly.
For example, I tried running it with the final element being the largest :
int data[] = {23, 8, 19, 35, 2, 12, 7, 64 };
Result : No sorting - the method hit the if (i >= j) {break;} with i==7 and j==6 straight off and so did nothing.
By contrast, the method in the answer I linked to above sorted correctly, so you can compare the method you have been given against that - or against other established articles (eg, do an internet search for java quicksort, there are plenty around)
As already noted by 'racraman', the sort definitely requires fixing.
Try re-implementing the sort function with the following method signature.
void sort(int[] arr, int leftIndex, int rightIndex) {
// swap code goes here
}
I have this code
public static void quicksort(int[] array){
quicksort(array, 0, array.length - 1);
}
public static void quicksort(int[] array, int min_index, int max_index){
if(array.length <= 1 || min_index >= max_index){
return;
}
int pivot = array[(max_index + min_index) / 2];
int left = min_index;
int right = max_index;
while(left <= right){
while(array[left] < pivot)
left++;
while(array[right] > pivot)
right--;
if( left <= right ){
int aux = array[left];
array[left] = array[right];
array[right] = aux;
left++;
right--;
}
}
if(right > min_index)
quicksort(array, min_index, right);
if(left < max_index)
quicksort(array, left, max_index);
}
Which works pretty fine, but if I change the pivot to pivot = array[0];, it breaks, giving me a stackoverflow exception. I tried other values, and it only seems to like the middle point. Why does this happen?
This is a well-known problem with Quicksort. For certain inputs, e.g. sorted (or almost sorted) data, and with poorly-selected pivot points, Quicksort will degenerate to a bubble-sort. Since the function is recursive, it is very easy to generate a stack overflow condition (or have the sort execute in O(n2) time). Text-book examples of Quicksort are notorious in this regard. Quicksort makes a nice programming exercise but you should always use the implementation provided with your compiler.
For more information on Quicksort, see the Wikipedia article.
I am trying to write code to determine the n smallest item in an array. It's sad that I am struggling with this. Based on the algorithm from my college textbook from back in the day, this looks to be correct. However, obviously I am doing something wrong as it gives me a stack overflow exception.
My approach is:
Set the pivot to be at start + (end-start) / 2 (rather than start+end/2 to prevent overflow)
Use the integer at this location to be the pivot that I compare everything to
Iterate and swap everything around this pivot so things are sorted (sorted relative to the pivot)
If n == pivot, then I think I am done
Otherwise, if I want the 4 smallest element and pivot is 3, for example, then I need to look on the right side (or left side if I wanted the 2nd smallest element).
-
public static void main(String[] args) {
int[] elements = {30, 50, 20, 10};
quickSelect(elements, 3);
}
private static int quickSelect(int[] elements2, int k) {
return quickSelect(elements2, k, 0, elements2.length - 1);
}
private static int quickSelect(int[] elements, int k, int start, int end) {
int pivot = start + (end - start) / 2;
int midpoint = elements[pivot];
int i = start, j = end;
while (i < j) {
while (elements[i] < midpoint) {
i++;
}
while (elements[j] > midpoint) {
j--;
}
if (i <= j) {
int temp = elements[i];
elements[i] = elements[j];
elements[j] = temp;
i++;
j--;
}
}
// Guessing something's wrong here
if (k == pivot) {
System.out.println(elements[pivot]);
return pivot;
} else if (k < pivot) {
return quickSelect(elements, k, start, pivot - 1);
} else {
return quickSelect(elements, k, pivot + 1, end);
}
}
Edit: Please at least bother commenting why if you're going to downvote a valid question.
This won't fix the issue, but there are several problems with your code :
If you do not check for i < end and j > start in your whiles, you may run into out of bounds in some cases
You choose your pivot to be in the middle of the subarray, but nothing proves that it won't change position during partitioning. Then, you check for k == pivot with the old pivot position, which obviously won't work
Hope this helps a bit.
Alright so the first thing I did was rework how I get my pivot/partition point. The shortcoming, as T. Claverie pointed out, is that the pivot I am using isn't technically the pivot since the element's position changes during the partitioning phase.
I actually rewrote the partitioning code into its own method as below. This is slightly different.
I choose the first element (at start) as the pivot, and I create a "section" in front of this with items less than this pivot. Then, I swap the pivot's value with the last item in the section of values < the pivot. I return that final index as the point of the pivot.
This can be cleaned up more (create separate swap method).
private static int getPivot(int[] elements, int start, int end) {
int pivot = start;
int lessThan = start;
for (int i = start; i <= end; i++) {
int currentElement = elements[i];
if (currentElement < elements[pivot]) {
lessThan++;
int tmp = elements[lessThan];
elements[lessThan] = elements[i];
elements[i] = tmp;
}
}
int tmp = elements[lessThan];
elements[lessThan] = elements[pivot];
elements[pivot] = tmp;
return lessThan;
}
Here's the routine that's calls this:
private static int quickSelect(int[] elements, int k, int start, int end) {
int pivot = getPivot(elements, start, end);
if (k == (pivot - start + 1)) {
System.out.println(elements[pivot]);
return pivot;
} else if (k < (pivot - start + 1)) {
return quickSelect(elements, k, start, pivot - 1);
} else {
return quickSelect(elements, k - (pivot - start + 1), pivot + 1, end);
}
}
I am trying to pass my implementation of the Quicksort through a tester; however, I get Array Index Out Of Bounds exception of -1 on the commended line
public void quickSort(ArrayList<String> data, int firstIndex,
int numberToSort) {
if (data.size() < 16) {
insertionSort(data, firstIndex, numberToSort);
} else {
int index = partition(data, firstIndex, numberToSort);
if (firstIndex < index - 1)
quickSort(data, firstIndex, index - 1);
if (numberToSort > index)
quickSort(data, index, numberToSort);
}
}
#Override
public int partition(ArrayList<String> data, int firstIndex,
int numberToPartition) {
String pivot = data.get(firstIndex);
int left = data.indexOf(firstIndex);
int right = data.indexOf(numberToPartition);
while (left <= right) {
while (data.get(left).compareTo(pivot) < 0) // this is where I get the error
left++;
while (data.get(right).compareTo(pivot) > 0)
right--;
if (left <= right) {
temp = data.get(left);
Collections.swap(data, left, right);
data.set(right, temp);
left++;
right--;
}
}
return left;
}
I have tried to debug my code but it seems that I just don't see a way to fix the error. Any help would be appreciated.
Why in the world are you doing
int left = data.indexOf(firstIndex);
int right = data.indexOf(numberToPartition);
? That looks for the the values of firstIndex and numberToPartition among the elements of the List being sorted. Those values are by no means certain to be present in the data, and even if they are, it is entirely coincidental. Their indices in the data are not meaningful.
In the event that one or both of those values is not present in the data, indexOf() returns -1, which you then happily pass to List.get().
It looks like what you want is more like
int left = firstIndex;
int right = firstIndex + numberToPartition - 1;
Make sure firstIndex does really occur in data, if not the .indexOf method returns -1 and you will get an java.lang.ArrayIndexOutOfBoundsException: -1 at int left = data.indexOf(firstIndex);
We have a collection of Comparables held in a bag and have to find the kth largest element. I copied the collection to a HashSet to remove duplicates, then converted the HashSet to an array to be sorted and consequently the kth element accessed. The code compiles, but fails the testing, and I can't figure out what's wrong. Any ideas?
public E kth(int k) {
uniqueSet();
Object[] uniqueArr = hashSet.toArray();
startQuick(uniqueArr);
return (E) uniqueArr[k - 1];
}
private void startQuick(Object[] uniqueArr) {
int i = 0, j = uniqueArr.length;
quickSort(uniqueArr, 0, j);
}
private void quickSort(Object[] uniqueArr, int i, int j) {
int index = partition(uniqueArr, i, j);
if (i < index - 1) {
quickSort(rankBagArr, index - 1, j);
}
if (index < j) {
quickSort(rankBagArr, i, index - 1);
}
}
private int partition(Object[] uniqueArr, int i, int j) {
E tmp;
E pivot = (E) rankBagArr[(i + j) / 2];
while (i <= j) {
while (rankBagArr[i].compareTo(pivot) < 0) {
i++;
}
while (rankBagArr[j].compareTo(pivot) > 0) {
j--;
}
if (i <= j) {
tmp = (E) rankBagArr[i];
rankBagArr[i] = rankBagArr[j];
rankBagArr[j] = tmp;
i++;
j--;
}
}
return i;
}
For a start this part is highly suspect:
if (i < index - 1)
quickSort(rankBagArr, index-1 ,j);
if (index < j)
quickSort(rankBagArr, i, index-1);
Don't you mean:
if (i < index - 1)
quickSort(rankBagArr, i, index-1);
if (index + 1 < j)
quickSort(rankBagArr, index + 1, j);
?
I'm not familiar with your approach to partitioning, so I don't know whether that's correct or not. I think I understand it, and it looks okay on inspection, but it's very easy to get off-by-one errors which are hard to see without careful study.
Here's a partition method I wrote in C# recently - you should be able to translate it into Java quite easily if you want to.
private static int Partition<T>(T[] array, int left, int right,
IComparer<T> comparer) {
// Pivot on the rightmost element to avoid an extra swap
T pivotValue = array[right];
int storeIndex = left;
for (int i = left; i < right; i++) {
if (comparer.Compare(array[i], pivotValue) < 0) {
Swap(array, i, storeIndex);
storeIndex++;
}
}
Swap(array, right, storeIndex);
return storeIndex;
}
static void Swap<T>(T[] array, int x, int y) {
T tmp = array[x];
array[x] = array[y];
array[y] = tmp;
}
Any reason for not just using Arrays.sort though?
If you want to solve the problem by sorting, then
Use sorting methods from API (Arrays.sort or Collections.sort). Reinventing the wheel is pointless.
Sort contents of your collection once, not every time you look for k-th element.
The quicksort partitioning is good for finding k-th element without sorting entire collection - you partition, if lowest range is larger then k, you recurrently go with partition to lower range, if it's smaller then k, you go to higher range and look for (k - size of lower range)-th element. It has better complexity than sorting whole collection. You can read more about it here
Anyway, your methods have parameter named uniqueArr, but some operations you perform on rankBagArr. Is it a typo? There is no definition of rankBagArr in your code.
May you could have a bit less of manipulations (and improve performance), and correct the default you are seeing...
Starting with a List (ArrayList), you could ask to sort it (using the comparator, and Collections.sort(list)). Then you could loop down and:
memorizing the last element
if you find the new element is not equals, increment a counter
when your counter reaches the k value, the current element is your target