Monday, August 6, 2018

DualPivotQuickSort in Java

This code is implemented and provided by Abdul Samad from AKG, college, Ghaziabad, UP, India.

Dual-Pivot Quicksort algorithm was given by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. It offers O(n log(n)) performance and is faster than traditional (one-pivot) Quicksort implementations.
please click on this link =>> click here to know more


//class to perform dual pivot quick sort.
public class DualPivotQuickSort
{
//method to swap elements of the array.
static void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

//sorting alogorithm implementation.
static void sorting(int[] a, int start, int end)
{
//base criteria or recursive condition. 
if (start < end)
{
int pivot1, pivot2, i, lt, gt, temp;
//To ensure that pivot1 is always smaller than pivot2.
//Pivot1 is always the starting element and pivot2 is always the last element of the array.
if (a[start] > a[end])
swap(a, start, end);

pivot1 = a[start];
pivot2 = a[end];

i = start + 1;
lt = start + 1;
gt = end - 1;

//loop for sorting.
while (i <= gt) 
{
        if (a[i] <= pivot1)
{
swap(a, i, lt);
lt++;
i++;
}
else if (a[i] >= pivot2)
{
swap(a, i, gt);
gt--;
}
else
i++;


swap(a, --lt, start);
swap(a, ++gt, end);

//Recursive calls.
//Recursive call from the starting index to the element preceding pivot1.

sorting(a, start, lt - 1);

//Recursive call from the index of the element following pivot1 to the index of the element //preceding pivot2.
sorting(a, lt + 1, gt - 1);

//Recursive call from the index of the element following pivot2 to the last index.
sorting(a, gt + 1, end);
}

}

public static void main(String[] args) 
{
// create an array that need to be sorted
int[] a = { 5, 4, 3, 2, 1, 19, 18, 17, 0, 0, 0, 13, 0, 99, -78, -98, 99, 5, 6 };

//Displaying original array.
System.out.println("Original Array-");
for (int i = 0; i < a.length; ++i)
{
System.out.print(a[i] + "\t");
System.out.println();
}

//calling sorting method
// a : is the name of array to be sorted
// 0 : is the index from which the sorting  
sorting(a, 0, a.length - 1);

//Displaying sorted array.
System.out.println("Sorted Array-");
for (int i = 0; i < a.length; ++i)
{
System.out.print(a[i] + "\t");
System.out.println();
}

} // end of main method

} // end of class


Output of code =>>

Original Array-
5
4
3
2
1
19
18
17
0
0
0
13
0
99
-78
-98
99
5
6
Sorted Array-
-98
-78
0
0
0
0
1
2
3
4
5
5
6
13
17
18
19
99
99

4 comments:

  1. Gajab....kya baat....kya baat....kya baat

    ReplyDelete
  2. Superb,Dual pivot very easy to understand nice comments in program.

    ReplyDelete
  3. Well commented and easy to understand code.. 👍👍

    ReplyDelete
  4. Fast sorting algorithm & easy to understand.

    ReplyDelete