Skip to content

Instantly share code, notes, and snippets.

@YusufAbdelaziz
Created March 28, 2020 21:06
Show Gist options
  • Save YusufAbdelaziz/9b24e12d4dfe53d2ebde5ce1f8148f0f to your computer and use it in GitHub Desktop.
Save YusufAbdelaziz/9b24e12d4dfe53d2ebde5ce1f8148f0f to your computer and use it in GitHub Desktop.
A faster quick sort with some recursive calls eliminated.
import java.util.Arrays;
import java.util.Random;
public class problemSolving {
static void RandomizedQuickSort(int[] array, int l, int r) {
//We first check if the left-most element index is greater than right-most element index
//This is considered as a base case to exit from infinite recursive calls
while (l < r) {
//Select a random number between l and r so you can prevent the unbalanced partitions as possible
Random rand = new Random();
//To generate a random number in a specific range, use (max-min+1) + min
int k = rand.nextInt(((r - l) + 1)) + l;
//Then swap A[k] with A[l] so we can reduce the possibilities of unbalanced partitions
swap(array, k, l);
//We then take the pivot element which may be a random one but we choose the first element for instance
var pivot = partition(array, l, r);
//Rather than making a lot of recursive call, try to eliminate some of them by choosing which one to make
//a call, the condition is basically test which side of sub-arrays is bigger, left hand side or right hand
//side, then we update the start or the end of the chosen sub-arrays.
if ((pivot - l) < (r - pivot)) {
RandomizedQuickSort(array, l, pivot - 1);
l = pivot + 1;
} else {
RandomizedQuickSort(array, pivot + 1, r);
r = pivot - 1;
}
}
}
static int partition(int[] array, int l, int r) {
//We make the first element of the array or sub-array be the pivot
var pivot = array[l];
//We make a counter which helps us to swap between smaller number and bigger number so smaller numbers
//go to the left of pivot and bigger ones go to the right
var j = l;
for (int i = l + 1; i <= r; i++) {
//If the element is smaller than the pivot, move the cursor 'j' to next element and make a swap.
if (array[i] <= pivot) {
j++;
swap(array, j, i);
}
}
//After you push the smaller elements to the right, then you make a swap to the 'j' element and the pivot
swap(array, j, l);
return j;
}
static void swap(int[] array, int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
public static void main(String[] args) {
int[] array = {6, 4, 2, 1, 4, 6, 7, 8, 30, 4, 3, 2, 9, 19, 3, 22, 1};
RandomizedQuickSort(array, 0, array.length - 1);
System.out.println(Arrays.toString(array));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment