|
| 1 | +package com.taobao.teadmin.notify.sender; |
| 2 | + |
| 3 | +import java.util.Random; |
| 4 | + |
| 5 | +/** |
| 6 | + * |
| 7 | + * Created by yixin on 2017-07-27. |
| 8 | + */ |
| 9 | +public class QuickSort { |
| 10 | + |
| 11 | + |
| 12 | + public static void main(String[] args) { |
| 13 | + |
| 14 | + int problemSize = 10; |
| 15 | + final Random random = new Random(); |
| 16 | + |
| 17 | + int[] data = new int[problemSize]; |
| 18 | + for(int i = 0; i < problemSize; i ++) { |
| 19 | + data[i] = random.nextInt(100); |
| 20 | + System.out.println(data[i]); |
| 21 | + } |
| 22 | + |
| 23 | + |
| 24 | + quickSort(data, 0, data.length - 1); |
| 25 | + |
| 26 | + |
| 27 | + System.out.println(" -- Sorted --"); |
| 28 | + for(int i = 0; i < problemSize; i ++) { |
| 29 | + System.out.println(data[i]); |
| 30 | + } |
| 31 | + |
| 32 | + } |
| 33 | + |
| 34 | + |
| 35 | + static void quickSort(int[] array, int left, int right) { |
| 36 | + // 判断条件很重要,否则会陷入递归爆炸 |
| 37 | + if(left < right) { |
| 38 | + int p = partition(array, left, right); |
| 39 | + quickSort(array, left, p - 1); |
| 40 | + quickSort(array, p + 1, right); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + static int partition(int a[], int i, int j) { |
| 46 | + int p = a[i]; // p is the pivot |
| 47 | + int m = i; // S1 and S2 are initially empty |
| 48 | + for (int k = i+1; k <= j; k++) { // explore the unknown region |
| 49 | + if (a[k] < p) { // case 2 |
| 50 | + m++; |
| 51 | + swap(a, m, k); |
| 52 | + } |
| 53 | + } |
| 54 | + swap(a, i, m); // final step, swap pivot with a[m] |
| 55 | + return m; // return the index of pivot, to be used by Quick Sort |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | + static void swap(int[] array, int m, int k) { |
| 60 | + int temp = array[m]; |
| 61 | + array[m] = array[k]; |
| 62 | + array[k] = temp; |
| 63 | + } |
| 64 | +} |
0 commit comments