Created
March 8, 2018 19:47
-
-
Save jeffrade/12597962a23d0eac3df8b80190f4866a to your computer and use it in GitHub Desktop.
An iterative implementation of Quick Sort in Java
This file contains 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
import java.util.Queue; | |
import java.util.LinkedList; | |
public class QuickSort { | |
private int[] arr; | |
private Queue<int[]> queue; | |
public QuickSort(int[] arr) { | |
super(); | |
this.arr = arr; | |
this.init(); | |
} | |
public void init() { | |
this.queue = new LinkedList<int[]>(); | |
queue.add(new int[] {0, arr.length - 1}); | |
} | |
public static void main(String[] args) { | |
int[] arr = new int[] {40,50,10,20,70,80,90,30,60}; | |
QuickSort sortApp = new QuickSort(arr); | |
sortApp.print(arr); | |
System.out.println("START"); | |
int[] sorted_arr = sortApp.sort(); | |
System.out.println("DONE"); | |
sortApp.print(sorted_arr); | |
} | |
public int[] sort() { | |
while(queue.size() > 0) { | |
int[] indexes = queue.remove(); | |
int left_index = indexes[0]; | |
int right_index = indexes[1]; | |
int index = partition(left_index, right_index); | |
if(left_index < index - 1) { | |
queue.add(new int[] {left_index, index - 1}); | |
} | |
if(index < right_index) { | |
queue.add(new int[] {index, right_index}); | |
} | |
} | |
return this.arr; | |
} | |
private int partition(int left, int right) { | |
int i = left; | |
int j = right; | |
int pivot_value = arr[(left + right) / 2]; | |
while(i <= j) { | |
while(arr[i] < pivot_value) { | |
i++; | |
} | |
while(arr[j] > pivot_value) { | |
j--; | |
} | |
if(i <= j) { | |
swap(i, j); | |
i++; | |
j--; | |
} | |
} | |
return i; | |
} | |
private void swap(int i, int j) { | |
int tmp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = tmp; | |
} | |
private void print(int[] a) { | |
int[] array = a == null ? this.arr : a; | |
for(int i = 0; i < array.length; i++) { | |
System.out.print(array[i] + ", "); | |
} | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment