Java实现快速排序算法

 1 package xiaoling;
 2 public class QuickSort{
 3         public static void main(String[] args){
 4                 int[] nums = new int[20];
 5                 for (int loc = 0; loc < nums.length; ++loc){
 6                         nums[loc] = (int) (Math.random() * 100) + 5;
 7                 }
 8                 for (int num: nums) System.out.print(num + " ");
 9                 System.out.println("
-----------------------");
10                 QS(nums, 0, nums.length-1);
11                 for (int num: nums) System.out.print(num + " ");
12                 System.out.println();
13         }
14         public static  void QS(int[] nums, int low, int high){
15                 if (low >= high) return;
16                 int mid = getMiddle(nums, low, high);
17                 QS(nums, mid+1, high);
18                 QS(nums, 0, mid-1);
19         }
20         public static int getMiddle(int[] nums, int low, int high){
21                 int temp = nums[low];
22                 while (low < high){
23                         while (low < high && nums[high] >= temp) --high;
24                         nums[low] = nums[high];
25                         while (low < high && nums[low] <= temp) ++low;
26                         nums[high] = nums[low];
27                 }
28                 nums[low] = temp;
29                 return low;
30         }
31 }

运行结果:Java实现快速排序算法