快速排序的代码
package test;
public class QuicklySort {
public static void main(String[] args) {
int[] arr = {2,3,-5,-2,0,1,8,7,4,5,66,1227,-6};
QuicklySort a = new QuicklySort();
a.quick(arr,0,arr.length-1);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
public int findPos(int[] arr,int low,int high,boolean reverse) {
int val = arr[low];
while(low<high) {
while(low<high && arr[high]<=val) {
high--;
}
arr[low]=arr[high];
while(low<high && arr[low]>=val) {
low++;
}
arr[high]=arr[low];
}
arr[high] = val;
return low;
}
public int findPos(int[] arr,int low,int high) {
int val = arr[low];
while(low<high) {
while(low<high && arr[high]>=val) {
high--;
}
arr[low]=arr[high];
while(low<high && arr[low]<=val) {
low++;
}
arr[high]=arr[low];
}
arr[high] = val;
return low;
}
public void quick(int[] arr,int low,int high) {
if (low<high) {
int pos = findPos(arr, low, high);
quick(arr,low,pos-1);
quick(arr,pos+1,high);
}
}
public void quick(int[] arr,int low,int high,boolean reverse) {
if (reverse) {
if (low<high) {
int pos = findPos(arr, low, high,true);
quick(arr,low,pos-1,true);
quick(arr,pos+1,high,true);
}
}else {
if (low<high) {
int pos = findPos(arr, low, high);
quick(arr,low,pos-1);
quick(arr,pos+1,high);
}
}
}
}