Sorting
Sorting puts the elements of an array in order. In interview problems, it is usually used when sorting the array makes the problem simpler.
Also, the techniques used in sorting algorithms often come up in other problems, so it is worth understanding how they work.
Bubble sort. O(n²) time.
Compare every two neighbours with two nested loops and swap them when they are in the wrong order, so every pass moves the greatest remaining element to the end.
In practice, bubble sort is too slow for large arrays. It is mostly used only as a teaching example.
Merge sort. O(n log n) time.
Split the array in half, sort each half, then merge them. Each half is sorted with the same steps, until an array has one element, which is already sorted.
To merge two sorted halves, start an i index at the first element of the left half and a j index at the first element of the right half.
Take the smaller of the two elements, add it to the merged array and move its index.
The technique of splitting the array recursively and then merging the halves is common in interview problems, often in a less obvious form than plain sorting.
The built-in sort functions in many programming languages use merge sort under the hood, because it is stable and takes time even in the worst case.
Quick sort. O(n log n) time on average.
Take any element as the pivot, and partition the array, putting the elements less than the pivot to the left, and the rest to the right.
This way the pivot ends up at the index it has in the sorted array. Then sort both sides of the pivot the same way.
The partition uses two indexes.
i iterates through the range, and j is the index where the next element less than the pivot goes, so every element before j is less than the pivot.
The time is on average, because a pivot usually splits the range into two parts of similar size. In the worst case it can be time.
The partition step is very common in interview problems, even when the problem is not about sorting.
Counting sort. O(n + k) time.
Create a separate array of length , the greatest value in the input array, so that every value from 0 to the greatest has its own index.
Count how many times every value appears, then write the values back in order.
This approach is fast when the number of possible values is not much greater than the length of the array.
The technique of counting values in a separate array of a fixed size is very common in interview problems when the number of possible values is small.