快速排序

 1 public class QuickSort {
 2     public void quickSort(int[] a, int left, int right){
 3         int i, j, t, temp;
 4         if (left > right)
 5             return;
 6         
 7         temp = a[left]; //哨兵
 8         i = left;
 9         j = right;
10         while (i != j){
11             while (a[j] >= temp && i < j) //从右往左找
12                 j--;
13             while (a[i] <= temp && i < j) //从左往右找
14                 i++;
15             
16             if (i < j){
17                 t = a[i];
18                 a[i] = a[j];
19                 a[j] = t;
20             }
21         }
22         
23         a[left] = a[i];
24         a[i] = temp;
25         
26         quickSort(a, left, i-1);
27         quickSort(a, i+1, right);
28     }
29     
30     public static void main(String[] args){
31         //int[] arr = {8, 3, 1, 0, 5, 6, 2, 7, 1};
32         int[] arr = {25, 15,27,99,18,35,14,66};
33         new QuickSort().quickSort(arr, 0, arr.length-1);
34         for(int i : arr){
35             System.out.println(i);
36         }
37     }
38 }

 

posted @ 2017-10-24 09:36  四季万花筒  阅读(216)  评论(0编辑  收藏  举报