I am working on a coms assignment and have hit a huge wall. We are working with quicksort / partition.
/**
* An implementation of the SELECT algorithm of Figure 1 of the project
* specification. Returns the ith order statistic in the subarray
* arr[first], ..., arr[last]. The method must run in O(n) expected time,
* where n = (last - first + 1).
*
* @param arr
* - The data to search in
* @param first
* - The leftmost boundary of the subarray (inclusive)
* @param last
* - The rightmost boundary of the subarray (inclusive)
* @param i
* - The requested order statistic to find
* @return - The ith order statistic in the subarray
*
* @throws IllegalArgumentException
* - If i < 1 or i > n
*/
public static int select(int[] arr, int first, int last, int i) {
if(first == last){
return first;
}
int pivot = (arr.length / 2);
pivot = partition(arr, first, last, pivot-1);
if(i == pivot){
return arr[i];
} else if(i < pivot){
return select(arr, first, pivot-1, i);
} else {
return select(arr, pivot+1, last, i);
}
}
The above is a 'select' method, I believe it is an implementation of quicksort. When I run it with my partition method, I keep getting errors of ArrayIndex out of bounds, I am wondering if the way I chose my pivot is causing these errors...
The below is a partition and a swap method I have written. The partition method works from what I can tell, I made a int[] of 10 and ran it multiple times, using different pivot points. Each time it threw out the arr sorted the way it should be.
public static int partition(int[] arr, int first, int last, int pivot){
int pValue = arr[pivot];
swap(arr, last, pivot);
int temp = first;
for (int i = first; i < last; i++) {
if(arr[i] < pValue){
swap(arr, temp, i);
temp++;
}
}
swap(arr, last, temp);
return arr[pivot];
}
public static void swap(int[] arr, int a, int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
The rest of the assignment builds off of the select method, and I have been slamming me head into a wall for two days to get it to work correctly.... To the point actually where I am second guessing my choice in degree. I guess as a secondary question how many of you guys hit these walls and lost all confidence in yourselves? The last few assignments, with a bit of help, made sense, but now I am here and just lost in the dark...
PS. Sorry if I sound all sappy, it's been a rough weekend and the above has been a huge pain.