Introduction of Sorting Techniques
Introduction of Sorting Techniques
1. Choose a pivot
2. Partition the array around pivot. After partition, it is ensured that all
elements are smaller than all right and we get index of the end point of
smaller elements. The left and right may not be sorted individually.
3. Recursively call for the two partitioned left and right subarrays.
Conquer:
[38] is already sorted.
[27] is already sorted.
[43] is already sorted.
[10] is already sorted.
Merge:
Merge [38] and [27] to get [27, 38] .
Merge [43] and [10] to get [10,43] .
Merge [27, 38] and [10,43] to get the final sorted list [10, 27, 38, 43]
Therefore, the sorted list is [10, 27, 38, 43] .
Working of Merge Sort algorithm:
To know the functioning of merge sort, lets consider an array arr[] = {38, 27, 43, 3, 9, 82, 10}
At first, check if the left index of array is less than the right index, if yes then calculate its mid point
Now, as we already know that merge sort first divides the whole array iteratively into equal halves,
unless the atomic values are achieved. Here, we see that an array of 7 items is divided into two arrays
of size 4 and 3 respectively.
Now, again find that is left index is less than the right index for both arrays, if found yes, then again
calculate mid points for both the arrays.
Now, further divide these two arrays into further halves, until the atomic units of the array is
reached and further division is not possible.
After dividing the array into smallest units, start merging the elements again based on comparison
of size of elements
Firstly, compare the element for each list and then combine them into another list in a sorted
manner.
After the final merging, the list looks like this:
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];