您可以使用以下的Java代码来实现快速排序算法: 6 u! Q, P b$ l# U6 ^8 X M7 c
- public class QuickSort {
" ^" v# {. W% h* G4 B7 Q" f& u
-
o! h4 V9 C7 o! `( S, |" Z+ R1 a
- public static void quickSort(int[] arr, int low, int high) {
- if (low < high) {
- int pivot = partition(arr, low, high);
% S( H @% a: G
- quickSort(arr, low, pivot - 1);
- quickSort(arr, pivot + 1, high);
- }
$ V e. B7 |. `5 B+ M- i1 ]; W3 a
- }
$ U" m. C/ _9 r7 w
-
- public static int partition(int[] arr, int low, int high) {
; S2 [/ ^6 D; F
- int pivot = arr[high];
- int i = low - 1;
3 u$ i$ y+ F6 a/ S3 ~+ Q
- for (int j = low; j < high; j++) {
- if (arr[j] < pivot) {
- i++;
- swap(arr, i, j);
- }
; e, o7 J" }8 P; u" F! Z4 u
- }
4 k! A7 ?0 v5 }% z8 W' ~
- swap(arr, i + 1, high);
- return i + 1;
- }
-
1 ^3 W/ R! L4 Z
- public static void swap(int[] arr, int i, int j) {
- int temp = arr[i];
1 e0 _" P5 b# H/ k
- arr[i] = arr[j];
- arr[j] = temp;
( m3 R8 A) ^! X7 U- l: t7 V
- }
* F3 a& i0 E& f/ q7 N, ?, `' x( N2 S
-
- public static void main(String[] args) {
- int[] arr = {9, 5, 1, 8, 3, 2, 7};
" ]1 O1 l9 H) J0 N0 y& }' j. w h
- quickSort(arr, 0, arr.length - 1);
" u( I6 S8 b6 p( m
- System.out.println("排序后的数组:");
- for (int num : arr) {
( `: I0 G% J. Z+ U' _
- System.out.print(num + " ");
. [, l' I! n8 r
- }
- }
" u w3 B/ N' U5 d" f/ u& K0 K: T! J# R
- }
复制代码
请注意,这只是快速排序算法的一种实现方式,您也可以使用其他方法来实现。, i6 i E- t9 g, r% n
. p6 F4 H7 y( I4 L& @- Z
! i5 u9 J5 W2 }* H2 P |