Skip to content

Instantly share code, notes, and snippets.

@YusufAbdelaziz
Created March 28, 2020 18:22
Show Gist options
  • Save YusufAbdelaziz/2d9b1a00a2e327156e9dec2b4775e7c0 to your computer and use it in GitHub Desktop.
Save YusufAbdelaziz/2d9b1a00a2e327156e9dec2b4775e7c0 to your computer and use it in GitHub Desktop.
Quick sort with random pivot in java
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
if (l >= r) {
return;
}
//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);
//We make two quick sort for left and hand side arrays recursively.
RandomizedQuickSort(array, l, pivot - 1);
RandomizedQuickSort(array, pivot + 1, r);
}
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