package in.malliktalksjava;

/**

* @author malliktalksjava

*

* Sort the given array using QuickSort Algorithm

*/

public class QuickSortExample {private int array[];

private int length;/**

* @param args

*

* Main Method. Calls the sort method and print the output into

* console.

*/

public static void main(String args[]) {

QuickSortExample quickSorter = new QuickSortExample();

int[] input = { 15, 42, 14, 100, 85, 1, 13, 6, 9 };

quickSorter.sortArray(input);

for (int count : input) {

System.out.print(count);

System.out.print(” “);

}

}/**

* @param inputArr

*

* Checks given array is empty or null, if not calls quickSort

* method.

*/

public void sortArray(int[] inputArr) {if (inputArr == null || inputArr.length == 0) {

return;

}

this.array = inputArr;

length = inputArr.length;

quickSort(0, length – 1);

}/**

* @param lowerIndex

* @param higherIndex

*

* Sorts the given array

*/

private void quickSort(int lowerIndex, int higherIndex) {int temp1 = lowerIndex;

int temp2 = higherIndex;

// calculate pivot number, here pivot is middle index number

int pivot = array[lowerIndex + (higherIndex – lowerIndex) / 2];

// Divide into two arrays

while (temp1 <= temp2) {

/**

* In each iteration, we will identify a number from left side which

* is greater then the pivot value, and also we will identify a

* number from right side which is less then the pivot value. Once

* the search is done, then we exchange both numbers.

*/

while (array[temp1] < pivot) {

temp1++;

}

while (array[temp2] > pivot) {

temp2–;

}

if (temp1 <= temp2) {

exchangeNumbers(temp1, temp2);

// move index to next position on both sides

temp1++;

temp2–;

}

}

// call quickSort() method recursively

if (lowerIndex < temp2)

quickSort(lowerIndex, temp2);

if (temp1 < higherIndex)

quickSort(temp1, higherIndex);

}/**

* @param param1

* @param param2

*

* Exchange the numbers and set to instance array variable

*/

private void exchangeNumbers(int param1, int param2) {

int temp = array[param1];

array[param1] = array[param2];

array[param2] = temp;

}

}

**Other Useful Links:**

Selection Sort Example Program in JAVA

Insertion Sort Example program in JAVA

[…] Quick Sort Example Program in Java […]

[…] Quick Sort Example Program in Java […]

[…] Quick Sort Example Program in Java […]

[…] Quick Sort Example Program in Java […]

I need to bookmark as I need a lot of java tutorials .. 🙂