Quick Sort Example in Java
On this page (9sections)
Introduction
Quick Sort is a classic Java console program that demonstrates the concept with complete source code and sample output. Sorting algorithms arrange data in order — bubble, selection, merge, quick and heap sort.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order. Quicksort is a comparison sort, meaning that it can sort items of any type for which a “less-than” relation (formally, a total order) is defined. In efficient implementations it is not a stable sort, meaning that the relative order of equal sort items is not preserved. Quicksort can operate in-place on an array, requiring small additional amounts of memory to perform the sorting.
Quick Sort Example Program
public class QuickSort {
public static void main(String[] args) {
int[] arry = { 56,44,78,32,95,06,31 };
System.out.println("Array before sorting: ");
for(int i=0;i= high){
return;
}
int middle = low + (high - low) / 2;
int pivot = arr[middle];
int i = low, j = high;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if (low < j){
quickSort(arr, low, j);
}
if (high > i){
quickSort(arr, i, high);
}
}
public static void printArray(int[] arry) {
System.out.println("After Sorting: ");
for (int a : arry)
System.out.println(a + " ");
System.out.println();
}
}
Sample Output
Array before sorting:
56
44
78
32
95
06
31
After Sorting:
06
31
32
44
56
78
95
When to use
Use this quick sort example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
int[] arry = { 56,44,78,32,95,06,31 };updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
A loop repeats the block until its condition becomes false.
-
int middle = low + (high - low) / 2;updates a variable used in the calculation or output. -
int pivot = arr[middle];updates a variable used in the calculation or output. -
int i = low, j = high;updates a variable used in the calculation or output. -
The
ifstatement runs the nested code only when the condition is true.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.