1、确定轴元素
2、左侧指针和右侧指针,循环移动,左侧寻找比轴大的元素,右侧寻找比轴小的元素
3、如果pl<pr,循环执行,反之停止循环
4、交换轴元素和r[pr]
5、递归处理左侧和右侧序列
代码如下:
package com.sor; import java.util.Random; public class TestQuickSort { //[2, 18, 85, 5, 34, 29, 70, 17, 62, 74] public static int[] quickSort(int[] r, int left, int right) { if (left < right) { int key = r[left]; int pl = left; int pr = right+1; while (true) { while (pl+1 < r.length&& r[++pl] < key) ; while (pr-1 > -1 && r[--pr] > key) ; if (pl > pr) { break; } swap(r, pl, pr); } // 交换轴元素 r[left] = r[pr]; r[pr] = key; // 递归,注意边界值,不是0和r.length-1 quickSort(r, left, pr - 1); quickSort(r, pr + 1, right); } return r; } private static void swap(int[] number, int i, int j) { int t; t = number[i]; number[i] = number[j]; number[j] = t; } public static void display(int[] R) { System.out.println(); for (int i = 0; i < R.length; i++) { System.out.print(R[i] + " "); } } public static void main(String[] args) { final int M = 10;// 定义数组大小为50 int[] R = new int[M]; for (int i = 0; i < M; i++) { R[i] = new Random().nextInt(100);// 生成100以内的随机数 } display(R); R = quickSort(R, 0, R.length - 1); display(R); } }