Skip to content

Instantly share code, notes, and snippets.

@dotspencer
Created February 18, 2016 01:42
Show Gist options
  • Save dotspencer/0076b52cc4263b48474d to your computer and use it in GitHub Desktop.
Save dotspencer/0076b52cc4263b48474d to your computer and use it in GitHub Desktop.
A class that contains static sorting methods. Including Quicksort.
package testing;
import java.util.Comparator;
public class Sorting {
public static <T> void quicksort(T[] array, Comparator<? super T> comp) {
quicksort(array, comp, 0, array.length - 1);
}
public static <T> void quicksort(T[] array, Comparator<? super T> c, int left, int right){
// Return if only one element
if(right - left < 1)
return;
int pivot = (right - left)/2 + left;
int wall = left;
swap(array, pivot, right); // Swap the pivot to the right
pivot = right; // Updates reference
for(int i = left; i < right; i++) {
if(c.compare(array[i], array[pivot]) < 0) { // If indicated element is smaller than the pivot, swap them and move up the pivot
swap(array, i, wall);
wall++;
}
}
swap(array, pivot, wall); // Puts pivot back in it's correct spot
pivot = wall; // Updates reference
quicksort(array, c, left, pivot - 1);
quicksort(array, c, pivot + 1, right);
}
public static <T> void swap(T[] array, int left, int right){
T temp = array[right];
array[right] = array[left];
array[left] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment