快速排序算法是冒泡排序的一种改进;
快速排序思想:先选取一个基准pivot,这里我们通常是选择第一个元素为基准,位置记为low;然后从右开始与基准进行比较,记右边的序号为high,依次向左扫描,若比基准大,high--;直到找到第一个比基准小的数,然后与基准进行位置交换。然后从基准的位置,在low+1的位置,从左到右扫描,若比基准小,low++;直到找到第一个比基准大的数,然后与基准交换位置;循环这个过程,直到排序完成。若low>=high,则排序结束。操作过程可以参照:http://blog.51cto.com/13733462/2113397,写的很清楚
Java程序如下:
package Sort;
public class QuickSortDemo {
public static void quickSort(int[] arr,int low,int high){
int pivot=0;
if(low>=high){
return;
}else{
pivot=sort(arr,low,high);
quickSort(arr, low, pivot);
quickSort(arr, pivot+1,high);
}
}
public static int sort(int[] arr,int low,int high){
int key=arr[low];
while(low<high){
while(low<high&&arr[high]>=key){
high--;
}
arr[low]=arr[high];
while(low<high&&arr[low]<=key){
low++;
}
arr[high]=arr[low];
}
arr[low]=key;
return low;
}
public static void main(String[] args) {
int[] arr={1,4,5,7,6,9,8,2,3};
System.out.println("未排序前数组为:");
for(int x:arr){
System.out.print(x+" ");
}
System.out.println();
quickSort(arr,0,arr.length-1);
System.out.println("排序后数组为:");
for(int x:arr){
System.out.print(x+" ");
}
}
}