Created
March 5, 2019 15:49
-
-
Save pedropedruzzi/bdf672ad8e80eebff0dc699503b7b3c1 to your computer and use it in GitHub Desktop.
Iterative QuickSort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package algorithms; | |
import java.util.Arrays; | |
import java.util.LinkedList; | |
import java.util.Random; | |
public class QuickSort { | |
private static class Interval { | |
int low; | |
int high; | |
Interval(int low, int high) { | |
this.low = low; | |
this.high = high; | |
} | |
boolean isNonEmpty() { | |
return high >= low; | |
} | |
} | |
public static void main(String[] args) { | |
Random random = new Random(); | |
Integer[] arrayLocalSort = new Integer[300]; | |
for (int i = 0; i < arrayLocalSort.length; i++) { | |
arrayLocalSort[i] = random.nextInt(1000); | |
} | |
Integer[] arrayJavaSort = Arrays.copyOf(arrayLocalSort, arrayLocalSort.length); | |
sort(arrayLocalSort); | |
Arrays.sort(arrayJavaSort); | |
//System.out.println("arrayLocalSort = " + Arrays.toString(arrayLocalSort)); | |
System.out.println("Results match? " + Arrays.equals(arrayLocalSort, arrayJavaSort)); | |
} | |
public static void sort(Object[] array) { | |
LinkedList<Interval> remainingIntervals = new LinkedList<>(); | |
remainingIntervals.add(new Interval(0, array.length - 1)); | |
while (!remainingIntervals.isEmpty()) { | |
Interval interval = remainingIntervals.pop(); | |
if (interval.isNonEmpty()) { | |
int pivotIndex = partition(array, interval); | |
remainingIntervals.add(new Interval(interval.low, pivotIndex - 1)); | |
remainingIntervals.add(new Interval(pivotIndex + 1, interval.high)); | |
} | |
} | |
} | |
private static int partition(Object[] array, Interval interval) { | |
Object pivotValue = array[interval.high]; | |
int writeIndex = interval.low; | |
// Swap values until all values less than pivotValue are at the beginning | |
for (int readIndex = interval.low; readIndex < interval.high; readIndex++) { | |
if (compare(array[readIndex], pivotValue) < 0) { | |
Object temp = array[writeIndex]; | |
array[writeIndex++] = array[readIndex]; | |
array[readIndex] = temp; | |
} | |
} | |
// Next writeIndex is the final pivot index. Swap with pivot and return | |
Object temp = array[writeIndex]; | |
array[writeIndex] = array[interval.high]; | |
array[interval.high] = temp; | |
return writeIndex; | |
} | |
private static int compare(Object o1, Object o2) { | |
return ((Comparable) o1).compareTo(o2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment