快速排序(Quicksort)是对冒泡排序的一种改进。基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中-部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列
package sort;
import java.util.Arrays;
public class 快速排序 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {-9,78,0,23,-567,70};
System.out.println(Arrays.toString(arr));
sort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
public static void sort(int[] arr,int left,int right) {
int left_index = left;//左下标
int right_index = right;//右下标
int temp = 0;//交换时使用
//中间的值
int pivot = arr[(left+right) / 2];
/**
* while循环目的是
*让比pivot中间值 小的放到左边,
*让比pivot中间值 大的放到右边,
*/
while(left_index < right_index){
//在pivot的左边一直找,找到大于等于pivot的值,然后退出while循环
while( arr[left_index] < pivot){
left_index++;
}
//在pivot的右边一直找,找到小于等于pivot的值,然后退出while循环
while( arr[right_index] > pivot){
right_index--;
}
//如果left_index >= right_index说明
//左边的值全部小于pivot值,右边全部是大于pivot的值
if(left_index >= right_index){
break;
}
//交换
temp = arr[left_index];
arr[left_index] = arr[right_index];
arr[right_index] = temp;
//交换完成后,发现arr[left_index] == pivot
if(arr[left_index] == pivot){
right_index--;
}
if(arr[right_index] == pivot){
left_index++;
}
}
if(left_index ==right_index){
left_index++;
right_index--;
}
//向左递归
if(left < right_index){
sort(arr, left, right_index);
}
if(right > left_index){
sort(arr, left_index, right);
}
}
}