Challenge: One Partition Step
Completed
Do one quick sort partition step using the last number as the pivot, exactly like the lesson (a “wall” that starts at the left, swap smaller items to the wall, then swap the pivot to the wall). Print the array after the step and then the pivot's final index.
Input
Line 1: n (n ≥ 1). Line 2: n whole numbers.
Output
Line 1: the array after partitioning. Line 2: pivot at <i>.
Example
Input
7 10 80 30 90 40 50 70
Output
10 30 40 50 70 90 80 pivot at 4
Editor
Java
Hints
pivot = a[n - 1]; wall = 0.
For each i before the pivot: if a[i] < pivot, swap a[i] with a[wall] and move the wall.
Solution explanation
One pass, O(n). After it, everything left of the pivot is smaller and everything right is at least as big.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
int pivot = a[n - 1], wall = 0;
for (int i = 0; i < n - 1; i++) {
if (a[i] < pivot) {
int t = a[i]; a[i] = a[wall]; a[wall] = t;
wall++;
}
}
int t = a[n - 1]; a[n - 1] = a[wall]; a[wall] = t;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) sb.append(i > 0 ? " " : "").append(a[i]);
System.out.println(sb);
System.out.println("pivot at " + wall);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module