Citi Interview Question

What's the difference between a bubble sort and quick sort?

Interview Answer

Anonymous

Oct 9, 2018

Bubble sort starts with the first element of an array and compares it to the subsequent element of the array. If the first element is larger than the next element, swap them. Loop until sorted. Bubble sort has O(n^2). Quick sort works by randomly selecting a pivot element in the array. Then, using the left most and right most elements of the array separately, iterate the left pointer to the right until it finds an element which is greater than the pivot. Then, iterate the right pointer to the left until you find an element which is less than the pivot, then swap the elements pointed to by the left and right pointers. Stop moving the pointers when they meet. This generally sorts the array into two sub-arrays. Call quick sort recursively on each half until the array is completely sorted. Quick sort has worst case O(n^2) when the pivot is the lowest value in the array each time, but has average O(n log n), which is much, much faster as n grows arbitrarily large.