Skip to content

Commit 3f3e319

Browse files
committed
Randomize Quick Sort Addition
1 parent 571d05c commit 3f3e319

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.randomized;
2+
3+
public class RandomizedQuickSort {
4+
5+
public static void randomizedQuickSort(int[] arr, int low, int high) {
6+
if (low < high) {
7+
int pivotIndex = partition(arr, low, high);
8+
randomizedQuickSort(arr, low, pivotIndex - 1);
9+
randomizedQuickSort(arr, pivotIndex + 1, high);
10+
}
11+
}
12+
13+
private static int partition(int[] arr, int low, int high) {
14+
int pivotIndex = low + (int) (Math.random() * (high - low + 1));
15+
int pivotValue = arr[pivotIndex];
16+
swap(arr, pivotIndex, high); // Move pivot to end
17+
int storeIndex = low;
18+
for (int i = low; i < high; i++) {
19+
if (arr[i] < pivotValue) {
20+
swap(arr, storeIndex, i);
21+
storeIndex++;
22+
}
23+
}
24+
swap(arr, storeIndex, high); // Move pivot to its final place
25+
return storeIndex;
26+
}
27+
28+
private static void swap(int[] arr, int i, int j) {
29+
int temp = arr[i];
30+
arr[i] = arr[j];
31+
arr[j] = temp;
32+
}
33+
34+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.thealgorithms.randomized;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class RandomizedQuickSortTest {
8+
@Test
9+
public void testRandomizedQuickSort() {
10+
int[] arr = {3, 6, 8, 10, 1, 2, 1};
11+
RandomizedQuickSort.randomizedQuickSort(arr, 0, arr.length - 1);
12+
int[] expected = {1, 1, 2, 3, 6, 8, 10};
13+
assertArrayEquals(expected, arr);
14+
}
15+
@Test
16+
public void testRandomizedQuickSortEmptyArray() {
17+
int[] arr = {};
18+
RandomizedQuickSort.randomizedQuickSort(arr, 0, arr.length - 1);
19+
int[] expected = {};
20+
assertArrayEquals(expected, arr);
21+
}
22+
@Test
23+
public void testRandomizedQuickSortSingleElementArray() {
24+
int[] arr = {5};
25+
RandomizedQuickSort.randomizedQuickSort(arr, 0, arr.length - 1);
26+
int[] expected = {5};
27+
assertArrayEquals(expected, arr);
28+
}
29+
30+
}

0 commit comments

Comments
 (0)