I want to modify QuickSort (in Java) so that every time Partition is called, the median of the proportioned array is used as the pivot.
I have a median selection algorit
You can use this ...
int Select(int array[],int start, int end,int k){
if(start==end){
return start;
}
int x=array[end];
int i=start-1;
for(int j=start;j<=end-1;j++){
if(array[j]<x){
i++;
Swap(array+i,array+j);
}
}
i++;
Swap(array+i,array+end);
if(i==k){
return i;
}
else if(i>k){
return Select(array,start,i-1,k);
}
else{
return Select(array,i+1,end,k);
}
}
Select will partition array on kth smallest element in array;
What you are looking for is the Selection Algorithm. Here's a link with pseudocode.
From the link:
In computer science, a selection algorithm is an algorithm for finding the kth smallest number in a list
To find the median you want to find the k=floor((n+1)/2) smallest number in the list where n is the size of the list.
The standard way to get the median is to sort the data. And you want to sort the data by partitioning on the median. This seems very chicken and egg to me.
Could you elaborate on why you want to partition/pivot on the median?
Note that in PARTITION
the pivot
is A[r]
.
public int QUICKSORT2(int[] A, int p, int r) {
if (p<r) {
int median=Math.floor((p + r) /2) - p + 1
int q=SELECT(A, p, r, median)
q=PARTITION2(A, p, r, q)
QUICKSORT2(A, p, q-1)
QUICKSORT2(A, q+1, r)
}
}
public int PARTITION2(int[]A, int p, int r, int q) {
int temp = A[r];
A[r]=A[q];
A[q]=temp;
return PARTITION(A, p, r)
}