首先我们来了解一下什么是快速排序算法呢?
快速排序算法实际上是对冒泡排序的一种改进,不知道大家对冒泡排序有没有一定的了解,简单的来说冒泡排序,它只是计算机科学领域的较简单的排序算法。
快速排序则是一种交换类的排序,它通过一趟排序把数据分割成两部分,其中的一份数据要小于另一份数据,然后在对这两部分数据进行快速排序,排序时可以使用递归(递归,就是在运行的过程中调用自己。),让整个数据变成有序序列(被排成一列的对象)。
详细图解:
![](https://i-blog.csdnimg.cn/blog_migrate/52539dd19bbe874d01e46db47a18c0b5.png)
快速排序用法:
public static void main(String[] args) {
/**
* java实现的快速排序算法
*/
int[] a = { 0, 3, 6, 8, 2, 4, 6, 9, 7, 5 };
new QuickSort().sort(a, 0, a.length - 1);
System.out.println(Arrays.toString(a));
}
public void sort(int[] a, int low, int high) {
if (low < high) {
int pivotIndex = position(a, low, high);
sort(a, low, pivotIndex - 1); // 左边序列。
sort(a, pivotIndex + 1, high); // 右边序列。
}
}
public int position(int a[], int low, int high) {
int pivot = a[low];
while (low < high) {
while (low < high && pivot <= a[high]) {
high--;
}
a[low] = a[high];
while (low < high && a[low] <= pivot) {
low++;
}
a[high] = a[low];
}
a[low] = pivot;
return low;
}
}
}
我们为什么要用快速排序算法?
因为在一般情况下,快速排序法比一般的排序方法能更为我们节省时间,所以快速排序在当前被认为是一种内部排序。