budd/budd-common/src/main/java/io/github/ehlxr/algorithm/sort/QuickSort.java

90 lines
2.8 KiB
Java
Raw Normal View History

2021-12-28 12:33:27 +00:00
/*
* The MIT License (MIT)
*
* Copyright © 2021 xrv <xrg@live.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.ehlxr.algorithm.sort;
import java.util.Arrays;
/**
* @author ehlxr
* @since 2021-12-28 19:57.
*/
public class QuickSort {
public static void main(String[] args) {
2021-12-28 16:21:10 +00:00
int[] a = new int[]{3, 9, 5, 7, 1, 2};
sort(a, 0, a.length - 1);
2021-12-28 12:33:27 +00:00
2021-12-28 16:21:10 +00:00
System.out.println(Arrays.toString(a));
2021-12-28 12:33:27 +00:00
}
2021-12-28 16:21:10 +00:00
public static void sort(int[] a, int p, int r) {
2021-12-28 12:33:27 +00:00
if (p >= r) {
return;
}
2021-12-28 16:21:10 +00:00
int q = partition(a, p, r);
2021-12-28 12:33:27 +00:00
2021-12-28 16:21:10 +00:00
sort(a, p, q - 1);
sort(a, q + 1, r);
2021-12-28 12:33:27 +00:00
}
2021-12-28 16:21:10 +00:00
/**
*
* <p>
* https://cdn.jsdelivr.net/gh/0vo/oss/images/quick_sort.jpg
* <p>
* i a[p...r]
* a[p...i-1] pivot a[i...r]
* a[i...r] a[j] pivot
* pivot a[i]
* <p>
* a[i] a[j] O(1) a[j] i
*/
public static int partition(int[] a, int p, int r) {
2021-12-28 12:33:27 +00:00
int i = p;
2021-12-28 16:21:10 +00:00
int pivot = a[r];
2021-12-28 12:33:27 +00:00
for (int j = p; j < r; j++) {
2021-12-28 16:21:10 +00:00
if (a[j] < pivot) {
swap(a, i++, j);
2021-12-28 12:33:27 +00:00
}
}
2021-12-28 16:21:10 +00:00
swap(a, i, r);
System.out.println("i=" + i + " " + Arrays.toString(a));
2021-12-28 12:33:27 +00:00
return i;
}
2021-12-28 16:21:10 +00:00
public static void swap(int[] a, int i, int j) {
if (i == j) {
return;
}
int temp = a[i];
a[i] = a[j];
a[j] = temp;
2021-12-28 12:33:27 +00:00
}
}