Created
August 11, 2019 18:26
-
-
Save RitamChakraborty/0f532b66d23886a39963aab199023dec to your computer and use it in GitHub Desktop.
Quick Sort algorithm 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
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