Skip to content

Instantly share code, notes, and snippets.

@RitamChakraborty
Created August 11, 2019 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RitamChakraborty/0f532b66d23886a39963aab199023dec to your computer and use it in GitHub Desktop.
Save RitamChakraborty/0f532b66d23886a39963aab199023dec to your computer and use it in GitHub Desktop.
Quick Sort algorithm in java
public class QuickSort {
private int[] arr;
public QuickSort(int[] arr) {
this.arr = arr;
}
public int[] sort() {
quickSort(0, arr.length - 1);
return arr;
}
private void quickSort(int start, int end) {
if (start < end) {
int pIndex = partition(start, end);
quickSort(start, pIndex - 1);
quickSort(pIndex + 1, end);
}
}
private int partition(int start, int end) {
int pivot = arr[end];
int pIndex = start;
for (int i = start; i < end; i++) {
if (arr[i] <= pivot) {
swap(i, pIndex);
pIndex++;
}
}
swap(pIndex, end);
return pIndex;
}
private void swap(int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment