此方法学习了别人的算法,感觉清晰明了了很多。
package sort;
public class quickSortDemo {
public static void main(String[] args) {
int[] arr = new int[]{101, 34, 119, 1, 52, 38, 67, 96, 23, 15, 2, 111};
quickSort(arr, 0, arr.length - 1);
for (int i : arr) {
System.out.print(i+",");
}
System.out.println();
}
private static void quickSort(int[] arr, int low, int high) {
if (low < high) {
//找寻基准数据的正确索引
int index = getIndex(arr, low, high);
quickSort(arr, low, index - 1);
quickSort(arr, index + 1, high);
}
}
private static int getIndex(int[] arr, int low, int high) {
//基准数据
int temp = arr[low];
while (low < high) {
//当队尾的元素大于等于基准数据时,向前挪动high指针
while (arr[high] >= temp && low < high) {
high--;
}
//如果队尾元素小于tmp,需要将其赋值给low
arr[low] = arr[high];
//当队首的元素小于等于基准数据时,向后挪动high指针
while (arr[low] <= temp && low < high) {
low++;
}
//如果队尾元素小于tmp,需要将其赋值给low
arr[high] = arr[low];
}
//跳出循环时,low和high相等,此时的low或者high就是tmp的正确索引位置
//但是此时的Low的位置的值并不是tmp,所以需要将tmp赋值给arr。
arr[low] = temp;
return low;
}
}
参考的文章链接:https://blog.csdn.net/nrsc272420199/article/details/82587933
https://wiki.jikexueyuan.com/project/easy-learn-algorithm/fast-sort.html