Added QuickSort algorithm.

This commit is contained in:
Alexey Zinchenko 2019-03-08 23:58:52 +03:00
parent d6f144a194
commit da6285c8a5
2 changed files with 43 additions and 4 deletions

View File

@ -1,9 +1,6 @@
package com.github.prominence.benchmark;
import com.github.prominence.sort.BubbleSort;
import com.github.prominence.sort.InsertionSort;
import com.github.prominence.sort.MergeSort;
import com.github.prominence.sort.SelectionSort;
import com.github.prominence.sort.*;
import org.openjdk.jmh.annotations.*;
import java.util.Arrays;
@ -56,4 +53,10 @@ public class SortingBenchmark {
public void mergeSort(MyState state) {
MergeSort.sort(state.getData());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void quickSort(MyState state) {
QuickSort.sort(state.getData());
}
}

View File

@ -0,0 +1,36 @@
package com.github.prominence.sort;
public class QuickSort {
public static void sort(int[] array) {
int startIndex = 0;
int endIndex = array.length - 1;
quickSort(array, startIndex, endIndex);
}
private static void quickSort(int[] array, int start, int end) {
if (start >= end) return;
int i = start, j = end;
int cur = i - (i - j) / 2;
while (i < j) {
while (i < cur && (array[i] <= array[cur])) {
i++;
}
while (j > cur && (array[cur] <= array[j])) {
j--;
}
if (i < j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
if (i == cur) {
cur = j;
} else if (j == cur) {
cur = i;
}
}
}
quickSort(array, start, cur);
quickSort(array, cur+1, end);
}
}