Quick Sort

medium Searching and Sorting

Problem

Read an array and print it sorted in ascending order. Use quick sort.

Constraints

  • 1 <= n <= 3000

Examples

Input

6
5 2 9 1 5 6

Output

1 2 5 5 6 9

Solutions

Best approachTime O(n log n) average, O(n^2) worstSpace O(log n) average

Pick a pivot, move smaller values left and bigger values right, then sort both sides. It is usually very fast. The worst case O(n^2) happens when the pivot is always the smallest or largest value (for example a sorted array with the last element as pivot).

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Sort an array in ascending order.
 * Input   : n, then n integers.
 * Output  : The sorted array.
 * Approach: Partition around a pivot.
 * Time    : O(n log n) average, O(n^2) worst
 * Space   : O(log n) average
 * Java    : 8 or newer.
 */
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
        // This method puts the pivot (the last element) at its final place.
        // Smaller values go to its left and bigger values go to its right. It returns the pivot index.
        static int partition(int[] a, int low, int high) {
            int pivot = a[high];
            int boundary = low;

            for (int i = low; i < high; i++) {
                if (a[i] < pivot) {
                    int temporary = a[i];
                    a[i] = a[boundary];
                    a[boundary] = temporary;
                    boundary++;
                }
            }

            int temporary = a[boundary];
            a[boundary] = a[high];
            a[high] = temporary;
            return boundary;
        }

        // This method sorts a[low..high] with quick sort.
        static void quickSort(int[] a, int low, int high) {
            // Step 1: A range with 0 or 1 element is already sorted.
            if (low >= high) {
                return;
            }

            // Step 2: Put the pivot at its final place, then sort both sides.
            int p = partition(a, low, high);
            quickSort(a, low, p - 1);
            quickSort(a, p + 1, high);
        }

    // This method solves the task. It receives the input and returns the answer.
    static int[] solve(int[] a) {
        quickSort(a, 0, a.length - 1);
        return a;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
    }
}
Hints (1)
  1. Where does the pivot stand after partitioning?