package com.algorithms;
import java.util.Arrays;
import java.util.Random;
public class QuickSort {
private static int count = 0;
public static void quickSort(Integer[] arr, int l, int r) {
if(l < r) {
int p = randomPartition(arr, l, r);
quickSort(arr, l, p - 1);
quickSort(arr, p + 1, r);
}
}
public static int randomPartition(Integer[] arr, int l, int r) {
int p = getRandomIndex(l, r);
exchange(arr, p, r);
return partition(arr, l, r);
}
public static int partition(Integer[] arr, int l, int r) {
int x = arr[r];
int i = l - 1;
for(int j = l; j < r; j++) {
count++;
if(arr[j] <= x) {
i = i + 1;
exchange(arr, i , j);
}
}
exchange(arr, i + 1, r);
return i + 1;
}
public static void exchange(Integer[] arr, int x, int y) {
int temp = 0;
temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
public static int getRandomIndex(int min, int max) {
Random random = new Random(37);
return random.nextInt(max)%(max-min+1) + min;
}
public static void main(String[] args) {
Integer arr[] = {12, 2, 10, 16, 5, 6, 8, 1, 9, 18};
// Integer arr[] = new Integer[30000000];
// Random random = new Random(37);
// for(int i = 0; i < 30000000; i++) {
// arr[i] = random.nextInt(100000000)%(100000000 - 0 + 1) + 0;
// }
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.asList(arr));
System.out.println(count);
}
}