Hello, learner! Today, we're delving into quick sort, a swift sorting algorithm akin to sorting toys by size. We'll explore how it works and implement it in TypeScript, so hang tight!
Quick sort, devised by Tony Hoare in 1959, leverages the divide-and-conquer strategy. It selects a pivot element and then arranges all smaller elements to one side and larger ones to the other.
Quick sort operates in three steps:
- Selecting a pivot.
- Shifting elements smaller than the pivot to one side and moving elements larger than the pivot to the other side.
- Repeating these steps for both sides separately.
Consider, for instance, sorting [3, 9, 4, 7, 5, 1, 6, 2, 8]
with 7
as the pivot. After one round, it becomes [3, 4, 5, 1, 6, 2, 7, 9, 8]
. The pivot 7
is correctly placed, and we can then divide the array into two parts: [3, 4, 5, 1, 6]
and [9, 8]
, which can be sorted separately.
Let's implement quick sort in TypeScript. First, we partition the array around the pivot in our partition
function:
