Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created September 11, 2016 13:20
Show Gist options
  • Save nichtemna/5b3ff3e704bb9bb74d74ed93690d8e7c to your computer and use it in GitHub Desktop.
Save nichtemna/5b3ff3e704bb9bb74d74ed93690d8e7c to your computer and use it in GitHub Desktop.
Quick sort
/**
*
* - Take first item of array and place it in position where all elements to left
* will be less or equals to the item and the all elements to right will
* be greater than the item, so we place it in its final position
- Than recursively do the same for the all elements in the left part and all elements in the right part and so on
*/
public class QuickSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
quickSort(array, 0, n - 1);
for (int i : array) {
System.out.print(i + " ");
}
}
private static void quickSort(int[] array, int start, int end) {
if (start >= end) {
return;
}
int position = partition(array, start, end);
quickSort(array, start, position - 1);
quickSort(array, position + 1, end);
}
private static int partition(int[] array, int start, int end) {
int pivot = array[start];
int position = start;
for (int i = start + 1; i <= end; i++) {
if (array[i] <= pivot) {
position++;
swap(array, position, i);
}
}
swap(array, position, start);
return position;
}
private static void swap(int[] array, int first, int second) {
int temp = array[first];
array[first] = array[second];
array[second] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment