快速排序是对于冒泡排序的改良
关于冒泡排序详见之前的博客:https://blog.csdn.net/szy2333/article/details/83118677
基本思想:
找一个数作为基数a,寻找这个基数的位置A,使位置A左边的元素的值均小于该基数a的值,该位置右边的元素的值军大于该基数a的值,然后以该基数a为准,将其左边的所有元素当做一个整体,并在这些元素中寻找一个基数b,寻找这个基数的位置B,使位置B左边的元素的值均小于该基数b的值,该位置右边的元素的值军大于该基数b的值(基数a右边和左边是一样的方法),然后不断迭代,直至每个元素左边的值都小于等于自己的值,右边的值都大于等于自己的值......使用递归的方式实现
图示过程:
对于基数6的左边和右边分别使用同样的方法过程,将每边的第一个数作为基数,然后确定该基数的位置,过程如下
继续上述方式,直至所有的数都到达自己正确的位置
代码如下:
排序代码
package 排序;
public class QuickSort {
public static void quickSort(int[] array, int lowIndex, int highIndex) {
//得到基数位置
int middleIndex = getMiddle(array, lowIndex, highIndex);
//对于基数左边的元素递归该方法
getMiddle(array, lowIndex, middleIndex - 1);
//对于基数左边的元素递归该方法
getMiddle(array, middleIndex + 1, highIndex);
}
public static int getMiddle(int[] array, int lowIndex, int highIndex) {
//将数组的第一个元素当做基数
int tmp = array[lowIndex];
//当lowIndex!=highIndex时,说明没有找到基数,则继续循环,调整位置
while (lowIndex < highIndex) {
//当基数小于等于以highIndex为下标的值时,highIndex不断左移
while (lowIndex < highIndex && tmp <= array[highIndex]) {
highIndex--;
}
//直至条件不成立,将array[highIndex]赋值给array[lowIndex]
array[lowIndex] = array[highIndex];
//当基数大于等于以lowIndex为下标的值时,lowIndex不断右移
while (lowIndex < highIndex && tmp >= array[lowIndex]) {
lowIndex++;
}
//直至条件不成立,将array[highIndex]赋值给array[lowIndex]
array[highIndex] = array[lowIndex];
}
//循环结束,即找到基数的位置,此时将该基数位置的值赋值为最初的基数值
array[lowIndex] = tmp;
return lowIndex;
}
}
测试代码
package 排序;
import static 排序.QuickSort.quickSort;
public class Test {
public static void main(String[] args) {
int[] array = new int[]{2, 9, 1, -5, 32, 31, 6, -5, 22, 0};
quickSort(array, 0, array.length - 1);
for(int i : array) {
System.out.println(i);
}
}
}