What Is Merge Sort
What Is Merge Sort
Divide: merge sort starts by dividing the input array into two halves. The algorithm recursively calls itself for
each of those halves until there are no half-arrays to divide during the sorting process.
Conquer: the algorithm sorts and merges the sub-arrays in this step to return an array whose values are sorted.
Generally, we use these high-level steps when sorting an array or a list with a merge sort:
Step 1: Check if the array has one element. If it does, it means all the elements are sorted.
Step 2: Use recursion to divide the array into two halves until we can't divide it anymore.
Step 3: Merge the arrays into a new array whose values are sorted.
using System;
OUTPUT: 3 2 1
What is Quicksort Algorithm?
Just like merge sort, quicksort uses the “divide and conquer” strategy to sort elements in arrays or lists. It
implements this strategy by choosing an element as a pivot and using it to partition the array.
The left subarray contains all elements that are less than the pivot. The right subarray contains all the elements that
are greater than the pivot. We recursively repeat this process until we sort the array. We can select the pivot the
algorithm uses during this process in different ways:
So, what is the best pivot to select when implementing the quicksort algorithm? The answer to this question is not
that simple.
Selecting the middle element of the unsorted array seems to make sense as it divides the array into equal
halves. However, the process of finding that middle element is difficult and time-consuming. Using this strategy
involves calculating the array’s length in every iteration and halving it to determine the index of the element in the
middle of the array.
On the other hand, when using the median element of the array as the pivot, we use the median-of-three technique
where we select the pivot based on the median of three values such as the first, middle, and last elements of the
array.
Therefore, selecting the first, last, random, or median element of the array as the pivot is the best approach.
In this article, let’s take the first element (51) as the pivot as we learn how to implement quicksort.
Next, we can see that 66 is greater than the pivot element while 41 is less than the pivot so we swap their positions:
As we traverse the array, 72 is greater than the pivot while 39 is less than the pivot so we swap their positions:
Given the fact that quicksort is recursive, in the next iteration, we are going to have two subarrays based on the
identified splitting points.
66, 72, 95
We are going to repeat the same process for the left subarray and select 38 as the pivot for that subarray. 14 is less
than the pivot while the rest of the elements are greater than the pivot so the array becomes:
39, 41, 42
We can see that by using the divide and conquer strategy we complete the sorting process efficiently with the result
being: