Hello, curious learners! Today, we will embark on a journey through the Quick Sort world. Picture yourself organizing various items — like toys or books — by size or color. That's what Quick Sort does with spectacular speed. Are you ready to explore further? Fantastic! Let's get started.
Quick Sort is a clever little algorithm invented by a British computer scientist named Tony Hoare in 1959. It uses a strategy called 'divide-and-conquer' to put elements in order. Quick Sort takes an array, selects a particular "pivot" element, and then places everything smaller than the pivot on one side and everything larger on the other.
Quick Sort has a three-step process:
- Pick a random "pivot" element from the array.
- Move all elements smaller than the pivot to one side and bigger ones to the other. This operation effectively divides the array into two parts, guaranteeing that all the elements will be kept within their part until the end of the sorting process.
- Repeat steps 1 and 2 for each part until there are no more unsorted elements.
For example, if we have nine marbles numbered [3, 9, 4, 7, 5, 1, 6, 2, 8] and our chosen marble, or pivot, is 7, then after one round of sorting, we'll get [3, 4, 5, 1, 6, 2, 7, 9, 8]. It seems that this is a minor change, but now the pivot element is in its correct position, and we can think of the first half of the array [3, 4, 5, 1, 6] and [9, 8] separately as they won't ever intersect again.
Let's translate these steps into a concrete C# program. We'll tackle it part by part. Our first step is to partition an array around a pivot. In C#, we need to write a method, let's call it Partition(), to handle this:
In this segment of the code, we selected the last element as the pivot and placed smaller elements on the left.
- The function starts by initializing
ito one index before thestart. Thisibasically keeps track of the latest position where an element has been swapped because it was less than or equal to the pivot. Ifarr[j]is less than or equal to the pivot,iis incremented and thenarr[j]is swapped witharr[i]. Essentially, smaller elements get pushed toward the front of the array (or the given part of the array).
The start and end parameters control which part of the given array is under the partition operation. Using these parameters, we can apply partition to some part of the array, which will be helpful later.
