'median quicksort using pivot
i have a question regarding my quicksort algorithm, it runs on small arrays but when the arrays get large the program quits running, basically I'm just trying to find the median value, so i keep splitting the array to discard values that I'm not worried about, so I'll use three values to find the best pivot and get that index, then i run quicksort so the values on either side are less or greater than pivot, and then check the pivot index with where the median value should be, for example if i have a 20 index array the median value should be 10, n if my pivot is at index 7 i start a new quicksort from index 7 to 20, n keep recursively running it until the pivotindex is at the median
// median of three
private static int getPivot(int[] nums, int left, int right) {
int[] triplet = new int[] {nums[left], nums[(left + right) / 2], nums[right]};
Arrays.sort(triplet);
// pivotIndex is either left, right, or middle
if(triplet[1] == nums[left]){
pivotIndex = left;
}
else if(triplet[1] == nums[(left + right) / 2]){
pivotIndex = (left + right) / 2;
}
else if(triplet[1] == nums[right]){
pivotIndex = right;
}
return triplet[1];
}
// swap two values
private static void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
/// this is the quick sort
Blockquote
static int median;
static int pivotIndex;
public static double findMedian(int[] nums) {
median = nums.length / 2;
quicksort(nums, 0, nums.length - 1);
return (nums[median]);
}
private static void quicksort(int[] nums, int left, int right) {
if (left >= right)
return;
int fromLeft = left;
int fromRight = right;
int pivot = getPivot(nums, left, right);
swap(nums, pivotIndex, right);
pivotIndex = right;
fromRight--;
while(fromLeft < fromRight){
if ( (nums[fromLeft] > pivot) && (nums[fromRight] < pivot)) {
swap(nums, fromLeft, fromRight);
fromLeft++;
fromRight--;
}
while (nums[fromLeft] < pivot){
fromLeft++;
}
while (nums[fromRight] > pivot){
fromRight--;
}
if( fromLeft > fromRight){
pivotIndex = fromLeft;
swap(nums, fromLeft, right);
}
}
if(pivotIndex == median){
return;
}
if(pivotIndex > median){
quicksort(nums, left, pivotIndex);
}
if(pivotIndex < median){
quicksort(nums, pivotIndex, right);
}
da problem i am having is when the number gets big enough is just says the application is running and doesn't do anything and i can't figure out why, even if it took n^2 it should eventually display an anser
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
