回答

收藏

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

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

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

! i5 u9 J5 W2 }* H2 P
关注下面的标签,发现更多相似文章
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则