← Home

912. Sort an Array

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
912

The trick here is to name the state correctly, then let the implementation follow. For 912. Sort an Array, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers.

The notes already sitting in the source point us in the right direction:

  • http://alrightchiu.github.io/SecondRound/comparison-sort-quick-sortkuai-su-pai-xu-fa.html

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are swap, partition, quickSort, sortArray.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//http://alrightchiu.github.io/SecondRound/comparison-sort-quick-sortkuai-su-pai-xu-fa.html
02//Runtime: 60 ms, faster than 93.26% of C++ online submissions for Sort an Array.
03//Memory Usage: 12.2 MB, less than 100.00% of C++ online submissions for Sort an Array.
04class Solution {
05public:
06    void swap(vector<int>& nums, int i, int j){
07        int tmp = nums[i];
08        nums[i] = nums[j];
09        nums[j] = tmp;
10    };
11    
12    int partition(vector<int>& nums, int left, int right){
13        int pivot = nums[right];
14        int i = left - 1; //the end of the subarray < pivot
15        for(int j = left; j < right; j++){
16            if(nums[j] < pivot){
17                //left part's size + 1
18                i++;
19                //now i points to the first element of right part
20                //swap right part's element and nums[j]
21                swap(nums, i, j);
22                //now i points to the last element of left part
23            }
24        }
25        i++;
26        //now i pionts to right part's first element
27        swap(nums, i, right);
28        return i;
29    };
30    
31    void quickSort(vector<int>& nums, int left, int right){
32        if(left < right){
33            int pivot = partition(nums, left, right);
34            quickSort(nums, left, pivot-1);
35            quickSort(nums, pivot+1, right);
36        }
37    };
38    
39    vector<int> sortArray(vector<int>& nums) {
40        quickSort(nums, 0, nums.size()-1);
41        return nums;
42    }
43};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.