Quick Sort in Java: Program and Logic
Sort an integer array in place with the quick sort algorithm.
- Time
O(n log n) average, O(n^2) worst case - Space
O(log n) average and O(n) worst case, for the recursion stack - Hints3
- Read2 min
Quick sort picks one element as the pivot, moves smaller values to its left and bigger values to its right, then sorts both sides the same way with recursion. It takes O(n log n) time on average and O(n^2) in the worst case. It sorts inside the same array, so no second array is needed.
Problem statement
Write a quick sort in Java program. You get an array of integers. Sort it from
smallest to largest, in place, without calling Arrays.sort.
For example, [7, 2, 9, 4, 5] must become [2, 4, 5, 7, 9].
An integer array arr of length n.
The same array, sorted in ascending order.
Examples
arr = [7, 2, 9, 4, 5][2, 4, 5, 7, 9]The pivot 5 lands at index 2, then the left and right sides are sorted.
arr = [3, -1, 3, 0, 8, -6][-6, -1, 0, 3, 3, 8]Negative numbers and the repeated 3 need no special handling.
Constraints
- 0 <= n <= 10^5
- Values fit in a 32-bit int and may repeat or be negative
Think before you code
Reveal the questions to ask yourself first
- If one element is already in its final place, what is left to sort?
- How can you move all smaller values to one side in a single pass?
- When should the recursion stop?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- Stop if the part has 0 or 1 element. It is already sorted.
- Pick a pivot. Here it is the last element.
- Partition. Walk through the part once. Swap every value that is
<= pivotinto the front zone. - Place the pivot just after that zone. It never moves again.
- Recurse on the left side and on the right side of the pivot.
This is different from merge sort, which splits first and does its work while joining. Quick sort does its work first, in the partition.
Dry run
Walk through the example step by step
First partition of [7, 2, 9, 4, 5], pivot 5:
value | <= 5? | action | array
------+-------+----------------------+----------
7 | no | skip | 7 2 9 4 5
2 | yes | swap with index 0 | 2 7 9 4 5
9 | no | skip | 2 7 9 4 5
4 | yes | swap with index 1 | 2 4 9 7 5
end | | pivot swaps to idx 2 | 2 4 5 7 9
Now 5 is fixed. Quick sort runs on [2, 4] and on [7, 9]. Both are already in order,
so nothing else changes.
Solution
Reveal the full Java solution
import java.util.Arrays;
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low >= high) {
return; // 0 or 1 element is already sorted
}
int p = partition(arr, low, high);
quickSort(arr, low, p - 1);
quickSort(arr, p + 1, high);
}
// Puts the last element in its final place and returns that index.
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1; // last index of the "smaller or equal" zone
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
private static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public static void main(String[] args) {
int[] a = {7, 2, 9, 4, 5};
quickSort(a, 0, a.length - 1);
System.out.println(Arrays.toString(a)); // [2, 4, 5, 7, 9]
int[] b = {3, -1, 3, 0, 8, -6};
quickSort(b, 0, b.length - 1);
System.out.println(Arrays.toString(b)); // [-6, -1, 0, 3, 3, 8]
}
}This quick sort in Java using recursion has two parts. partition puts one value in its
final place. quickSort repeats that for the two sides. After every partition one more
value is fixed, so the array ends up sorted.
Quick sort in Java: first element as pivot
Some questions ask for the first element as pivot. Only the partition method changes. One pointer looks for a bigger value from the left, the other for a smaller value from the right, and the two are swapped.
static int partitionFirst(int[] arr, int low, int high) {
int pivot = arr[low];
int i = low + 1;
int j = high;
while (true) {
while (i <= j && arr[i] <= pivot) i++; // find a bigger value
while (i <= j && arr[j] > pivot) j--; // find a smaller value
if (i > j) break;
swap(arr, i, j);
}
swap(arr, low, j); // pivot moves to its final place
return j;
}
For [7, 2, 9, 4, 5] this places 7 at index 3 and gives [4, 2, 5, 7, 9]. The rest of
the quick sort in Java code stays the same.
Why the worst case is slow
If the array is already sorted, the first or last element is always the smallest or the
biggest. One side is then empty each time, so the work grows to O(n^2) and the recursion
goes n levels deep. A big sorted array can even cause a StackOverflowError. Picking
a random pivot makes this unlikely. Many equal values are also a bad case for this code.
Where to go next
Compare this quick sort in Java example with insertion sort, practise binary search on the sorted result, and read the DSA interview questions. To learn with a trainer, see the Java full stack course.
O(n log n) average, O(n^2) worst caseO(log n) average and O(n) worst case, for the recursion stackReview before the interview
Common mistakes
- Calling quickSort(arr, low, p) instead of p - 1. The pivot is included again and the recursion may never end.
- Writing low == high as the stop check. An empty part has low > high, so use low >= high.
- Forgetting the last swap that puts the pivot in its place.
Edge cases to test
- An empty array: high is -1, so the method returns at once.
- An already sorted array is the slow case for a first or last pivot.
- All values equal: every value goes to one side, so it also takes O(n^2).
Interview follow-ups
- How would you choose a random pivot?
- Is quick sort stable? Can you show two equal values changing order?
- How does three-way partitioning help when many values are equal?
Keep practising
Merge Two Sorted Arrays Into One Sorted Array
Hints · Dry run · SolutionSolve Similar problemCheck Whether an Array Is Sorted
Hints · Dry run · SolutionSolve Similar problemSegregate 0s and 1s in an Array
Hints · Dry run · SolutionSolve Related learningArrays
TutorialLearn Related learningCoding Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
