回答

收藏

如何用java实现快速排序算法

知识点 知识点 181 人阅读 | 0 人回复 | 2023-12-04

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

: p( |2 o9 e  I, T  G* y
关注下面的标签,发现更多相似文章
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则