Skip to content

Instantly share code, notes, and snippets.

@scientific-coder
Created October 8, 2018 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scientific-coder/188798122695e6f552d612b434539655 to your computer and use it in GitHub Desktop.
Save scientific-coder/188798122695e6f552d612b434539655 to your computer and use it in GitHub Desktop.
public static void swap(int[] data, int i, int j){
int tmp= data[i];
data[i]= data[j];
data[j]= tmp;
}
public static int partition(int[] data, int begin, int end, int pivotIdx){
swap(data, pivotIdx, --end);
pivotIdx= end;
int pivot= data[pivotIdx];
//invariant is that everything before begin is known to be < pivot
// and everything after end is known to be >= pivot
while(begin != end){
if(data[begin] >= pivot){
swap(data, begin, --end);
}else{
++begin;
}
}
swap(data, pivotIdx, begin);
return begin;
}
public static void sort(int[] data){
sort(data, 0, data.length);
}
public static void sort(int[] data, int begin, int end){
if((end-begin) < 2){ return; }
int m= partition(data, begin, end, (end+begin)/2);
sort(data, begin, m);
sort(data, m+1, end); // +1 for convergence (ref:quick-recur)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment