1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| class QuickSort<T extends Comparable>{
public static void main(String[] args) { QuickSort<Integer> quickSort = new QuickSort<>(); Integer[] arr = new Integer[]{1,6,2,3,88,-2,6,2,8,0,5,9,7}; quickSort.sort(arr); System.out.println("-----"); quickSort.show(arr); }
public void sort(T[] arr){ sort(arr,0, arr.length - 1); }
public void sort(T[] arr, int l, int r){ if(l >= r){ return; } int i = partation1(arr, l, r); sort(arr, l, i - 1); sort(arr, i + 1, r); }
public int partation(T[] arr, int l, int r){ int i = l-1; int j = r; T t = arr[r]; while(true){ while(less(arr[++i], t)){ if(i == r){ break; } } while (less(t, arr[--j])){ if(j == l){ break; } } if(i >= j){ break; } exch(arr, i , j); } exch(arr, r, i); return i; }
public int partation1(T[] arr, int l, int r){ int i = l; int j = r + 1; T t = arr[l]; while(true){ while(less(arr[++i], t)){ if(i == r){ break; } } while (less(t, arr[--j])){ if(j == l){ break; } } if(i >= j){ break; } exch(arr, i , j); } exch(arr, l, j); return j; }
private boolean less(T t1, T t2){ return t1.compareTo(t2) < 0; }
private void exch(T[] a, int i, int j){ T tmp = a[i]; a[i] = a[j]; a[j] = tmp; }
public void show(T[] arr){ for(T t : arr){ System.out.println(t); } } }
|