Skip to content

Instantly share code, notes, and snippets.

@Alfex4936
Created September 29, 2020 14:20
Show Gist options
  • Select an option

  • Save Alfex4936/bd04682bd2732269e4ee4cba67d591a0 to your computer and use it in GitHub Desktop.

Select an option

Save Alfex4936/bd04682bd2732269e4ee4cba67d591a0 to your computer and use it in GitHub Desktop.
Quick Sort using Tail recursive, Hoare partition scheme, Insertion Sort in Java
package csw;
import java.util.Random;
public class Quick {
public static void main(String[] args) {
Random rd = new Random();
Double[] test = new Double[500_000];
for (int i = 0; i < test.length; i++) {
test[i] = rd.nextDouble();
}
long startTime = System.nanoTime();
Double[] result = quickSort(test, 0, test.length - 1);
long stopTime = System.nanoTime();
double elapsedTimeInSecond = (double) (stopTime - startTime) / 1_000_000_000;
System.out.println("Took: " + elapsedTimeInSecond + "s");
// System.out.println(Arrays.toString(result));
boolean sorted = isSorted(result);
System.out.println(sorted);
}
private static <T extends Comparable<T>> T[] quickSort(T[] array, int low, int high) {
while (high > low && high - low > 16) {
int p = partition(array, low, high);
quickSort(array, low, p);
low = p + 1;
}
return insertSort(array, low + 1, high + 1);
}
private static <T extends Comparable<T>> int partition(T[] array, int low, int high) {
T pivot = array[(low + high) / 2];
int i = low - 1;
int j = high + 1;
while (true) {
i++;
while (less(array[i], pivot)) {
i++;
}
j--;
while (greater(array[j], pivot)) {
j--;
}
if (i >= j) {
return j;
}
swap(array, i, j);
}
}
private static <T extends Comparable<T>> T[] insertSort(T[] array, int low, int high) {
for (int i = low; i < high; i++) {
int j = i;
while (j > 0 && less(array[j], array[j - 1])) {
swap(array, j, j - 1);
j--;
}
}
return array;
}
private static <T extends Comparable<T>> boolean isSorted(T[] array) {
for (int i = 0; i < array.length - 1; i++) {
if (greater(array[i], array[i + 1])) {
return false;
}
}
return true;
}
private static <T> void swap(T[] array, int idx, int idy) {
T swap = array[idx];
array[idx] = array[idy];
array[idy] = swap;
}
private static <T extends Comparable<T>> boolean less(T v, T w) {
return v.compareTo(w) < 0;
}
private static <T extends Comparable<T>> boolean greater(T v, T w) {
return v.compareTo(w) > 0;
}
}
Took: 0.1778896s
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment