Quicksort in Python

Reading time ~1 minute

Time complexity: O(nlog(n)) for average case. Worst case O(n^2). Usually better than other nlog(n).

The idea is really simpe and adheres ‘divide and conquer’ paradigm:

  1. choose 1st element as a pivot
  2. put elems that bigger to ‘high’ group and qsort it //recursion
  3. put elems that smaller in ‘low’ group and qsort it //recursion
  4. base case: return if only 1 elem

Writing it in python takes only few lines:

1
2
3
4
5
6
7
8
9
10
11
12
def qsort(arr):
    print arr
    if len(arr) < 2:
        return arr
    pivots = [x for x in arr if x == arr[0]]
    lo = qsort([x for x in arr if x < arr[0]])
    hi = qsort([x for x in arr if x > arr[0]])

    return lo + pivots + hi

array = [11, 50, 2, 43, 6, 100, 8, 20, 3, 15]
print qsort(array)

How to Download Multiple Instagram Photos at Once?

You want to print your Insta photos or just keep them save and archived? Out of luck - there is no obvious way to download them, unless y...… Continue reading

Polymer and Vulcanization

Published on August 08, 2016

Jeff Dean of Google

Published on August 06, 2016