您可以使用以下的Java代码来实现快速排序算法: w$ B, A" s( H# f+ p( I
- public class QuickSort {
-
( Z7 s' q* W5 }% i; x2 }+ W; o' @
- public static void quickSort(int[] arr, int low, int high) {
6 v! P8 G% u* D4 _2 f) d
- if (low < high) {
, _( E6 e# i3 a0 \8 N
- int pivot = partition(arr, low, high);
& P7 V+ _3 p" P+ b
- quickSort(arr, low, pivot - 1);
- quickSort(arr, pivot + 1, high);
- }
5 S( V' G" s* B- h" B* x
- }
-
- public static int partition(int[] arr, int low, int high) {
! U$ c" m8 [8 [- v! M* m
- int pivot = arr[high];
- int i = low - 1;
% p$ C6 D0 o# x7 H5 ]( s3 X7 v6 t
- for (int j = low; j < high; j++) {
: H" D0 R! s4 v7 U% t$ Q8 |
- if (arr[j] < pivot) {
- i++;
' x- Z+ L: L8 @8 F
- swap(arr, i, j);
- }
- }
- swap(arr, i + 1, high);
- return i + 1;
- }
, c* y6 V) c& z' e
-
: E- J7 [0 s+ C: q& C' P" w" |
- public static void swap(int[] arr, int i, int j) {
- int temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
1 q( F( o( K- r
-
# X4 f0 N* l/ o) k
- public static void main(String[] args) {
- int[] arr = {9, 5, 1, 8, 3, 2, 7};
- quickSort(arr, 0, arr.length - 1);
( @- A% |$ T( | w: b
- System.out.println("排序后的数组:");
/ G& [' G- l( d4 V
- for (int num : arr) {
- System.out.print(num + " ");
- }
: q( _& \1 o* z9 \9 z) R) J0 }8 V
- }
- }
, r0 ?* R0 G( t- o, ^* @; t
复制代码
请注意,这只是快速排序算法的一种实现方式,您也可以使用其他方法来实现。& i' Z1 d7 ?1 z
% W3 {; ?; h9 ]/ R% ^1 h4 H* P8 {- G$ X% `& S5 J' ~
|