排序思想:
设置两个搜索指针start和end,它们分别指向首尾,
从end位置开始搜索比支点小的记录,并将其交换到start位置处,start向后移动一个位置,
然后从start位置开始搜索比支点大的位置,并将其交换到end位置处,end向前移动一个位置
如此继续,直到start和end相等结束,这时支点前面的数全小于它,后面全比它大,
然后将支点前面和后面的序列继续进行排序,直到完成排序.
代码如下:
public class QuickSort {
public static void main(String[] args) {
int[] arr = new int[10];
Random r = new Random();
//随机生成十组数据进行排序
for(int j = 0;j<10;j++){
for(int i = 0;i<arr.length;i++){
arr[i] = r.nextInt(50);
}
System.out.println("原数组: ");
System.out.println(Arrays.toString(arr));
quickSort(arr,0,arr.length-1);
System.out.println("快速排序后的数组: ");
System.out.println(Arrays.toString(arr));
}
}
private static void quickSort(int[] arr, int i, int j) {
int start = i;
int end = j;
int t = 0;
if(start < end){
t = arr[start];
while(start<end){
while(t<=arr[end] && start<end){
end--;
}
if(start<end){
arr[start] = arr[end];
start++;
}
while(t>=arr[start] && start < end){
start++;
}
if(start<end){
arr[end] = arr[start];
end--;
}
}
arr[start] = t;
quickSort(arr,i,start-1);
quickSort(arr,start+1,j);
}
}
}