基本思想:
通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后在按此方法对这两部分分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据都变成有序序列。
本质上,快速排序是对冒泡排序的一种改进。
Java实现(递归方式)
public void qiuckSort(int[] arr, int low, int hight) {
if(low> =hight){
return;
}
int index = findIndex(arr, low, hight);
qiuckSort(arr, low, index -1);
qiuckSort(arr, index +1, hight);
}
public int findIndex(int[] arr, int low, int hight) {
int temp = arr[low];
while (low < hight) {
while (low < hight && arr[hight] >= temp) {
hight--;
}
arr[low] = arr[hight];
while (low < hight && arr[low] <= temp) {
low--;
}
}
arr[hight] = arr[low];
arr[low] = temp;//还原基准值
return low;//跳出循环时,low==hight,返回谁也无所谓
}
网友评论