Skip to content

Commit 4fe494d

Browse files
Completed the QuickSort implementation using the recursive algo approach
1 parent 8308a41 commit 4fe494d

2 files changed

Lines changed: 45 additions & 3 deletions

File tree

‎src/com/sketch/Main.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
package com.sketch;
22

3-
import com.sketch.sort.selectionsort.SelectionSort;
3+
import com.sketch.sort.quicksort.QuickSort;
44

55
import java.util.Arrays;
66
import java.util.Random;
77

88
public class Main {
99
public static void main(String[] args){
10-
int[] unsortedArray = new int[20];
10+
int[] unsortedArray = new int[100];
1111
Random random = new Random();
1212
for(int i = 0; i < unsortedArray.length; i++){
1313
unsortedArray[i] = random.nextInt(20);
@@ -16,7 +16,7 @@ public static void main(String[] args){
1616
int[] unsortedArrayResult = new int[unsortedArray.length];
1717
System.arraycopy(unsortedArray, 0, unsortedArrayResult, 0, unsortedArray.length);
1818

19-
unsortedArrayResult = SelectionSort.sort(unsortedArrayResult);
19+
QuickSort.sort(unsortedArrayResult, 0, unsortedArrayResult.length - 1);
2020

2121
System.out.println("Actual Value Index: " + Arrays.toString(unsortedArray));
2222
System.out.println("Actual Value Index: " + Arrays.toString(unsortedArrayResult));
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.sketch.sort.quicksort;
2+
3+
import java.util.Random;
4+
5+
public class QuickSort {
6+
public static void sort(int[] unsortedArray, int lowIndex, int highIndex){
7+
if(lowIndex >= highIndex){
8+
return;
9+
}
10+
int pivotIndex = new Random().nextInt(highIndex - lowIndex) + lowIndex;
11+
int pivot = unsortedArray[pivotIndex];
12+
swap(unsortedArray, pivotIndex, highIndex);
13+
int leftPointer = partition(unsortedArray, lowIndex, highIndex, pivot);
14+
15+
sort(unsortedArray, lowIndex, leftPointer - 1);
16+
sort(unsortedArray, leftPointer + 1, highIndex);
17+
}
18+
19+
private static int partition(int[] unsortedArray, int lowIndex, int highIndex, int pivot){
20+
int leftPointer = lowIndex;
21+
int rightPointer = highIndex;
22+
23+
while(leftPointer < rightPointer){
24+
while (unsortedArray[leftPointer] <= pivot && leftPointer < rightPointer){
25+
leftPointer++;
26+
}
27+
while(unsortedArray[rightPointer] >= pivot && leftPointer < rightPointer){
28+
rightPointer--;
29+
}
30+
swap(unsortedArray, leftPointer, rightPointer);
31+
}
32+
swap(unsortedArray, leftPointer, highIndex);
33+
34+
return leftPointer;
35+
}
36+
37+
private static void swap(int[] array, int a, int b){
38+
int temp = array[a];
39+
array[a] = array[b];
40+
array[b] = temp;
41+
}
42+
}

0 commit comments

Comments
 (0)