面试常见排序–快速排序的多种实现方法
一、普通方法
public static int quickSort(int[]array,int low,int high) {
int i,j,k,t;
if(low>high) {
return -1;
}
i=low;
j=high;
k=array[i];
while(i<j) {
while(i<j&&k<=array[j]) {
j--;
}
while(i<j&&k>=array[i]) {
i++;
}
if(i<j) {
swap(array, i, j);
}
}
array[low]=array[i];
array[i]=k;
return i;
quickSort(array, low, i-1);
quickSort(array, i+1, high);
}
public static void swap(int[] array,int i,int j) {
int k=array[i];
array[i]=array[j];
array[j]=k;
}
二、首次中轴为随机数
public static int getMiddle(int[] numbers,int low,int high) {
int temp=numbers[low];
while(low<high) {
while(low<high&&numbers[high]>=temp) {
high--;
}
numbers[low]=numbers[high];
while(low<high&&numbers[low]<=temp) {
low++;
}
numbers[high]=numbers[low];
}
numbers[low]=temp;
return low;
}
public static int randPartion(int[]a ,int i,int j) {
Random random=new Random();
int l=random.nextInt(j-i)+i;
swap(a, l,i );
return getMiddle(a, i, j);
}
public static void quickSort2(int[] numbers,int low,int high) {
if(low<high) {
int middle=randPartion(numbers, low, high);
quickSort2(numbers, low, middle-1);
quickSort2(numbers, middle+1, high);
}
}
三、非递归方法
public static int getMiddle(int[] numbers,int low,int high) {
int temp=numbers[low];
while(low<high) {
while(low<high&&numbers[high]>=temp) {
high--;
}
numbers[low]=numbers[high];
while(low<high&&numbers[low]<=temp) {
low++;
}
numbers[high]=numbers[low];
}
numbers[low]=temp;
return low;
}
public static int randPartion(int[]a ,int i,int j) {
Random random=new Random();
int l=random.nextInt(j-i)+i;
swap(a, l,i );
return getMiddle(a, i, j);
}
public static void quickSort3(int[] numbers,int low,int high) {
LinkedList<Integer>stack=new LinkedList<>();
if(low<high) {
stack.push(low);
stack.push(high);
while(!stack.isEmpty()){
int r=stack.pop();
int l=stack.pop();
int middle=quickSort(numbers, l, r);
if(l<middle-1) {
stack.push(l);
stack.push(middle-1);
}
if(r>middle+1) {
stack.push(middle+1);
stack.push(r);
}
}
}
}