既然开了算法和数据结构一栏,那么这些算法还是要重新再写一遍,其实平时都看过,也都研究过,就是没有形成文档,现在发现在写博客时,还是要斟酌下应该怎么去写,自己也发现现在和几年前看的时候感觉完全不一样了,说不出的感觉。
原理:
找出一个基准数A,将序列里比A小的放左边,比A大的放右边。然后递归。
样例:
第一次交换找出30的基础位置是index = 3:
第二次就以index = 3 为界限进行左边一半的左右递归过程:
交换流程:
①先从队尾开始向前扫描且当low < high时,如果a[high] > tmp,则high–,
如果a[high] < tmp,则将high的值赋值给low,即arr[low] = a[high],
同时要转换数组扫描的方式,即需要从队首开始向队尾进行扫描了
②同理,当从队首开始向队尾进行扫描时,如果a[low] < tmp,则low++,
如果a[low] > tmp了,则就需要将low位置的值赋值给high位置,即arr[high] = arr[low],
同时将数组扫描方式换为由队尾向队首进行扫描.
③不断重复①和②,直到low>=high时(其实是low=high),low或high的位置就是该基准数据在数组中的正确索引位置。
代码实现:
public class QuickSort {
public static void main(String[] args) {
int[] arr = { 30, 50, 40, 10, 20, 80, 5};
quickSort(arr, 0, arr.length - 1);
for (int i : arr) {
System.out.print(i+" ");
}
}
private static void quickSort(int[] arr, int low, int high) {
if (low < high) {
// 找寻基准数据的正确索引
int index = getIndex(arr, low, high);
for (int i : arr) {
System.out.print(i+" ");
}
// 进行迭代对index之前和之后的数组进行相同的操作使整个数组变成有序
quickSort(arr, 0, index - 1);
quickSort(arr, index + 1, high);
}
}
private static int getIndex(int[] arr, int low, int high) {
// 基准数据
int tmp = arr[low];
while (low < high) {
while (low < high && arr[high] >= tmp){
high--;
}
// 找到小于的元素 赋值给arr[low]
arr[low] = arr[high];
while (low < high && arr[low] <= tmp) {
low++;
}
// 找到大于的元素 赋值给arr[high]
arr[high] = arr[low];
}
// 跳出循环时low和high相等,此时的low或high就是tmp的正确索引位置
arr[low] = tmp;
return low; // 返回tmp的正确位置
}
}