|
1 | 1 | package com.mistray.swapsort; |
2 | 2 |
|
| 3 | +import com.mistray.model.SortModel; |
| 4 | + |
3 | 5 | /** |
4 | 6 | * @author MistLight |
5 | 7 | * @create 2018-11-19 |
6 | | - * @desc 快速排序 |
| 8 | + * @desc 快速排序->分治算法 |
| 9 | + * 逻辑: |
| 10 | + * 1.i =L; j = R; 将基准数挖出形成第一个坑a[i] |
| 11 | + * 2.j--由后向前找比它小的数,找到后挖出此数填前一个坑a[i]中 |
| 12 | + * 3.i++由前向后找比它大的数,找到后也挖出此数填到前一个坑a[j]中 |
| 13 | + * 4.再重复执行2,3二步,直到i==j,将基准数填入a[i]中 |
7 | 14 | */ |
8 | 15 | public class QuickSort { |
9 | 16 | public static void main(String[] args) { |
10 | | - |
11 | | - |
| 17 | + Integer[] arr = {8, 34, 5, 92, 44, 2, 74, 12}; |
| 18 | + QuickSort.quickSort(arr, 0, arr.length - 1); |
| 19 | + SortModel.show(arr); |
12 | 20 | } |
13 | 21 |
|
14 | | - public static void quickSort(Integer[] quc){ |
| 22 | + /** |
| 23 | + * 递归的方式实现快速排序 |
| 24 | + * |
| 25 | + * @param arr 无序数组a |
| 26 | + */ |
| 27 | + public static void quickSort(Integer[] arr, Integer start, Integer end) { |
| 28 | + if (start < end) { |
| 29 | + int index = partition(arr, start, end); |
| 30 | + quickSort(arr, start, index - 1); |
| 31 | + quickSort(arr, index + 1, end); |
| 32 | + SortModel.show(arr); |
| 33 | + } |
| 34 | + } |
15 | 35 |
|
| 36 | + private static int partition(Integer[] arr, Integer start, Integer end) { |
| 37 | + //arr[start]为挖的第一个坑arr[start]为8 |
| 38 | + int key = arr[start]; |
| 39 | + while (start < end) { |
| 40 | + // 从arr[end]开始向前找一个比arr[start]小或相等的数填到arr[end]小的数(arr[5])填到arr[start]的位置 |
| 41 | + while (arr[end] >= key && end > start) { |
| 42 | + end--; |
| 43 | + } |
| 44 | + // 逆向查找找到[5] |
| 45 | + arr[start] = arr[end]; |
| 46 | + // {2,34,5,92,44,2,74,12} |
| 47 | + SortModel.show(arr); |
| 48 | + // 这时又出现了一个新坑(arr[5]),从arr[start]开始向后找一个比arr[5]大的数(arr[1])填到arr[5]的位置 |
| 49 | + while (arr[start] <= key && end > start) { |
| 50 | + start++; |
| 51 | + } |
| 52 | + // 正向查找找到[1] |
| 53 | + arr[end] = arr[start]; |
| 54 | + SortModel.show(arr); |
| 55 | + // 所以会再次进入循环找[1]与[5]未确认的部分,直到start<end为止,将k填进对应的位置 |
| 56 | + } |
| 57 | + arr[start] = key; |
| 58 | + return start; |
16 | 59 | } |
| 60 | + |
17 | 61 | } |
0 commit comments