We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

Close

You are in Guest Mode!

What you can do in guest mode:

  • Read the lessons
  • Watch the videos

What you can not do in guest mode:

  • Run your code
  • Submit your answers
  • Save your progress
  • View solutions
  • Get help from Boots
  • Take quizzes
  • Unlock achievements and roles

You're on assignment part 1/2 for this lesson.

Quick Sort Big O

On average, quicksort has a Big O of O(n*log(n)). In the worst case, and assuming we don't take any steps to protect ourselves, it can degrade to O(n^2). partition() has a single for-loop that ranges from the lowest index to the highest index in the array. By itself, the partition() function is O(n). The overall complexity of quicksort is dependent on how many times partition() is called.

Worst case: The input is already sorted. An already sorted array results in the pivot being the largest or smallest element in the partition each time, meaning partition() is called a total of n times.

Best case: The pivot is the middle element of each sublist which results in log(n) calls to partition().

Reference

def quick_sort(nums, low, high):
    if low < high:
        p = partition(nums, low, high)
        quick_sort(nums, low, p - 1)
        quick_sort(nums, p + 1, high)


def partition(nums, low, high):
    pivot = nums[high]
    i = low
    for j in range(low, high):
        if nums[j] < pivot:
            nums[i], nums[j] = nums[j], nums[i]
            i += 1
    nums[i], nums[high] = nums[high], nums[i]
    return i