对于一个初级程序员的我一直对算法不是很吃透,所以这几天补习了一些排序算法。
这篇博文分析快速排序的思想和实现。
如有错误请大家指正!!!
1.快速排序的思想
通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
2.快速排序的实现
package com.imun.test.sort;
public class NumSort {
private static int[] numArr = {54, 26, 93, 17, 77, 31, 44, 55, 20};
public static void quickSort(int start, int end) {
if (start >= end) {
return;
}
// mid为基数
int mid = numArr[start];
// 低位
int lowIndex = start;
// 高位
int highIndex = end;
while (lowIndex < highIndex) {
// 从高位对比基数
while (lowIndex < highIndex && numArr[highIndex] > mid) {
highIndex--;
}
numArr[lowIndex] = numArr[highIndex];
// 从低位对比基数
while (lowIndex < highIndex && numArr[lowIndex] < mid) {
lowIndex++;
}
numArr[highIndex] = numArr[lowIndex];
}
numArr[lowIndex] = mid;
// 递归从基数左边的数组进行快速排序
quickSort(start, lowIndex - 1);
// 递归从基数右边的数组进行快速排序
quickSort(lowIndex + 1, end);
}
public static void main(String[] args) {
quickSort(0, numArr.length - 1);
for (int num : numArr) {
System.out.print(num + "\t");
}
}
}