您可以使用以下的Java代码来实现快速排序算法: ) E" o. B: E2 f# C8 `) ?" [
- public class QuickSort {
4 ^3 ^/ X( C) D$ i& v; T1 `, L5 F; d3 d
-
8 ]( |4 E; P2 |& m* u& y" x
- public static void quickSort(int[] arr, int low, int high) {
, J1 _0 ]! E4 U& u% D$ E
- if (low < high) {
- int pivot = partition(arr, low, high);
' f5 `1 x' H1 Q
- quickSort(arr, low, pivot - 1);
- quickSort(arr, pivot + 1, high);
) }% d: f0 `+ t$ l' e
- }
- }
( P! k& G8 P: ~) ^. l0 ]0 `2 Y
-
- public static int partition(int[] arr, int low, int high) {
- int pivot = arr[high];
) L/ [+ o' `! X+ ~1 x/ w) S0 e
- int i = low - 1;
0 j5 q$ t5 j' X- B" C- f
- for (int j = low; j < high; j++) {
6 I* C2 S, E$ A' c5 [- q
- if (arr[j] < pivot) {
1 X5 `! g4 e1 ]
- i++;
- swap(arr, i, j);
' Z% ^$ p4 y* o% d/ C
- }
- }
- swap(arr, i + 1, high);
( E0 b0 x4 n4 v+ @2 D0 P+ A K( x4 [
- return i + 1;
- }
-
0 Y# I6 s$ a% T9 x( s
- public static void swap(int[] arr, int i, int j) {
- int temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
-
/ H/ a9 Z. [2 V; l' Z
- public static void main(String[] args) {
' R- C- C4 k- T( m
- int[] arr = {9, 5, 1, 8, 3, 2, 7};
- quickSort(arr, 0, arr.length - 1);
- System.out.println("排序后的数组:");
- for (int num : arr) {
- System.out.print(num + " ");
- }
4 t1 v: n1 g% u [% a l0 E; D
- }
( _/ E/ \3 ]9 H* r5 K
- }
复制代码
请注意,这只是快速排序算法的一种实现方式,您也可以使用其他方法来实现。
! ?. y4 a. I. \) u. ^3 e- ]: k5 v* p: f$ L0 n7 c8 ?
: p( |2 o9 e I, T G* y |