クイックソートの2つのバージョン


 1 package com.book.sword_offer;
 2 
 3 import java.util.Arrays;
 4 
 5 public class quicksort_p64 {
 6 
 7     public static void main(String[] args) {
 8         int[] arr = { 5, 1, 2, 6, 7, 0, 4, 12, 2, 43, 1, 1, 1 };
 9         new solution_2().quick_sort(arr, 0, arr.length - 1);
10         System.out.println(Arrays.toString(arr));
11     }
12 
13 }
14 
15 class solution {
16     void quick_sort(int[] arr, int start, int end) {
17         int k = partion(arr, start, end);
18         if (k > start) {
19             quick_sort(arr, start, k - 1);
20         }
21         if (k < end) {
22             quick_sort(arr, k + 1, end);
23         }
24     }
25 
26     int partion(int[] arr, int start, int end) {
27         int i = start;
28         int j = end;
29 
30         int k = arr[start];
31         while (i < j) {
32             while (i < j && arr[j] >= k) {
33                 j--;
34             }
35             arr[i] = arr[j];
36             while (i < j && arr[i] <= k) {
37                 i++;
38             }
39             arr[j] = arr[i];
40         }
41         arr[i] = k;
42         return i;
43     }
44 }
45 
46 class solution_2 {
47 
48     void quick_sort(int[] arr, int start, int end) {
49         int k = partion(arr, start, end);
50         if (k > start) {
51             quick_sort(arr, start, k - 1);
52         }
53         if (k < end) {
54             quick_sort(arr, k + 1, end);
55         }
56     }
57 
58     int partion(int[] arr, int start, int end) {
59         int pivotpos = start;
60         int pivot = arr[start];
61         for (int i = start + 1; i <= end; i++) {
62             if (arr[i] < pivot && ++pivotpos != i) {
63                 int tmp = arr[i];
64                 arr[i] = arr[pivotpos];
65                 arr[pivotpos] = tmp;
66             }
67         }
68 
69         int tmp = arr[start];
70         arr[start] = arr[pivotpos];
71         arr[pivotpos] = tmp;
72 
73         return pivotpos;
74     }
75 }