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);
Related
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 have written my version of the Quick Sort in Java but I'm running into a bit of a problem while calling the second recursion. This is my code:
public static int[] quickSort(int[] array, int start, int end) {
int pIndex;
if (start < end) {
int left = start;
int right = end - 1;
int pivot = array[end];
//Start the partitioning
while (left < right) {
if (array[left] > pivot && array[right] < pivot) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
left++;
right--;
} else if (array[left] > pivot)
right--;
else
left++;
}
if (array[end] < array[left]) {
int temp = array[left];
array[left] = array[end];
array[end] = temp;
pIndex = left;
} else
pIndex = end;
//End partitioning
quickSort(array, 0, pIndex - 1);
quickSort(array, pIndex + 1, array.length - 1);
}
return array;
}
The parameter start will be the index of the first element in the array and end will be the index of the last one and I am picking the last element as the pivot.
The issue I am running into is at quickSort(array, pIndex + 1, array.length - 1);
The array.length-1 causes this to go on infinitely since it is with reference to the original array. Is there any way for me to fix this without having to pass a new array to the function everytime?
I did try to create a global variable to store the new lengths but I wasn't able to do it quite right.
Thanks in advance.
I'm sorry if the code is not a very nice implementation of the Sort. I wanted to write one from scratch on my own but turns out I ran into problems anyway.
The proper way of using recursion in QuickSort is to use start, pivot and end.
You appear to be using inclusive-end indexing; then you will want to recurse into
quicksort(data, start, pivot - 1)
quicksort(data, pivot + 1, end)
The pivot element is already in its final position.
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--;
}
I am facing some problem with the recursive quick sort algorithm. The elements are not sorted in the correct order. The input data are Strings with duplicate entries as well. I am using an integer to differentiate between ascending order( 1 ) and descending order ( -1) sort. The pivot is the mid element. Whenever the duplicate entries are compared( compareTo(String s) will return 0), i compare the current indices and return a negative number if the index of the string being compared is more than the index of the other.I am not sure as to what exactly is going wrong.
Below is the code
// Quick sort Algorithm
public void sort(int left, int right)
{
int i = left, j = right;
String mid;
mid = (String)vect.elementAt((left + right)/2);
while (i <= j)
{
// Compare the elements to the left
while ((i < right) &&
(compare((String)vect.elementAt(i), mid) < 0))
i++;
// Compare the elements to the right
while ((j > left) && (compare((String)vect.elementAt(j), mid) > 0))
j--;
if (i <= j)
{
if(i!=j)
swap(i, j);
i++;
j--;
}
}
// Recursively call the sort method until indices cross.
if(left < j)
sort(left, j);
if(i < right)
sort(i, right);
}
/*
* Compare method to compare the elements.
* type = 1, for ascending sort
* type = -1, for descending sort
*/
public int compare(String firstObj, String secondObj)
{
int resCompare = firstObj.compareTo(secondObj)*type;
if(resCompare == 0)
{
int index_firstObj = vect.indexOf(firstObj);
int index_secObj = vect.indexOf(secondObj);
if(index_firstObj < index_secObj)
return -1;
else
return 1;
}
return resCompare;
}
// Swap the elements at i and j.
public void swap(int i, int j)
{
String tmp1 = (String)vect.elementAt(i);
String tmp2 = (String)vect.elementAt(j);
vect.setElementAt(tmp1, j);
vect.setElementAt(tmp2, i);
}
Example :
input = {"AA","BB","zz","cc","aa","AA","PP","hh" };
Ascending sort
output = {"AA","AA","BB","PP","aa","cc","hh","zz"};
Descending sort
output = {"zz","hh","cc","BB","aa","PP","AA","AA"};
The problem in the algorithm may not work for ascending order sort as well on some other input data. So any help in finding the glitch in the code/logic will be really helpful.Thanks in advance.
Solved:
There is no need to find index_firstObj and index_SecondObj. Just don't do anything if the resCompare is zero.
public int compare(String firstObj, String secondObj)
{
int resCompare = firstObj.compareTo(secondObj)*type;
return resCompare;
}
What if i or j become the mid? and the other one is yet not the mid? doesnt that arise problems also? You might need to check if one of them becomes the mid.
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