QuickSort Implementation In Java

This is a working solution of Quick Sort algorithm in Java. I haven’t written the main method. You can add it & call quickSort(arr, 0, arr.length – 1) with your custom input array. Hope this Java program is self-explanatory.

 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
import java.util.*;
import java.lang.*;
import java.io.*;


class Solution
{
//Function to sort an array using quick sort algorithm.
static void quickSort(int arr[], int low, int high)
{
if(low >= high){
return;
}
int sortedIndex = partition(arr, low, high);
quickSort(arr, low, sortedIndex - 1);
quickSort(arr, sortedIndex + 1, high);
}

static int partition(int arr[], int low, int high)
{
int pivot = high;

/* keeps track of the current index where left-hand side
elements are less than pivot element*/
int index = low;

for(int i=low; i < high; i++){
if(arr[i] < arr[pivot]){
swap(arr, i, index);
index++;
}
}

swap(arr, pivot, index);
return index;
}

private static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

Leave a Comment