-
Notifications
You must be signed in to change notification settings - Fork 0
/
InplaceQuick.java
76 lines (59 loc) · 2.07 KB
/
InplaceQuick.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
Date: 11th May,2017
@Author: Naren Vaishnavi
Inplace Quick Sort
*/
package InplaceQuick;
import java.util.Arrays;
import java.util.Random;
public class InplaceQuick {
private static final Random random = new Random();
private static final int RANDOM_INT_RANGE = 100000;
public static void main(String[] args) {
long time1 = System.currentTimeMillis();
System.out.print("Time Taken:" + time1);
int[] arr = assignValues(100000);
System.out.println("Before Sorting " + Arrays.toString(arr));
if (arr.length > 0) {
inPlaceQuick(arr, 0, arr.length - 1);
}
System.out.println("Sorted array: " + Arrays.toString(arr));
long time = System.currentTimeMillis();
System.out.print("Time Taken:" + time);
}
private static int[] assignValues(int size) {
final int[] arr = new int[size];
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(RANDOM_INT_RANGE);
}
return arr;
}
private static void inPlaceQuick(int[] arr, int left, int right) {
if (left >= right) {
return; // sorted
}
final int range = right - left + 1;
int pivot = random.nextInt(range) + left;
int newPivot = InplacePartition(arr, left, right, pivot);
inPlaceQuick(arr, left, newPivot - 1);
inPlaceQuick(arr, newPivot + 1, right);
}
private static int InplacePartition(int[] arr, int left, int right, int pivot) {
int pivotVal = arr[pivot];
swap(arr, pivot, right);
int indexValue = left;
for (int i = left; i <= (right - 1); i++) {
if (arr[i] < pivotVal) {
swap(arr, i, indexValue);
indexValue++;
}
}
swap(arr, indexValue, right);
return indexValue;
}
private static void swap(int[] arr, int from, int to) {
int temp = arr[from];
arr[from] = arr[to];
arr[to] = temp;
}
}