我们常见的有很多排序算法,比如冒泡排序,插入排序等等,今天我们介绍一下关于快速排序的内容。
快速排序的时间复杂度为:O(Nlogn)是一种较其他算法更快的一种算法。它的实现方式为,首先找到一个数值,作为一个标准。例如,在数组arr中,选取arr[0]作为标准,然后需要有两个指针left,和right,left负责从左向右扫描,right负责从右往左扫描,如果发现比标准值小,就要放到标准值的左边,如果比标准值大,就要放到标准值的右边,在这个过程中,left一直想右,2️⃣right一直向左,当left和right重合时,说明遍历结束,经过这次排序之后,在arr[0]的左边都是比它小的数,在arr[0]右边都是比它大的数。
经过这次排序之后,我们可以思考,arr[0]的位置已经被确定,那么我们就可以根据递归的思想来对arr[0]左边的数组用同样的方法进行排列,同样的arr[0]右边也是如此,下面我们看一下代码。
import java.util.*;
public class Main {
static int N = 100010;
static int[] q = new int[N];
static void quick_sort(int[] q, int l, int r) {
if (l >= r) return;
int x = q[(l + r ) >> 1] , i = l - 1, j = r + 1;
while (i < j) {
do i ++; while (q[i] < x);
do j --; while (q[j] > x);
if (i < j) {
int t = q[i];
q[i] = q[j];
q[j] = t;
}
}
quick_sort(q, l, j);
quick_sort(q, j + 1, r);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i ++) {
q[i] = sc.nextInt();
}
quick_sort(q, 0, n - 1);
for (int i = 0; i < n; i ++) {
System.out.print(q[i] + " ");
}
}
}