sorting algorithms explained part 2

Selection Sort Algorithm

Selection sort algorithm starts by compairing first two elements of an array and swapping if necessary, i.e., if you want to sort the elements of array in ascending order and if the first element is greater than second then, you need to swap the elements but, if the first element is smaller than second, leave the elements as it is. Then, again first element and third element are compared and swapped if necessary. This process goes on until first and last element of an array is compared. This completes the first step of selection sort.
If there are n elements to be sorted then, the process mentioned above should be repeated n-1 times to get required result. But, for better performance, in second step, comparison starts from second element because after first step, the required number is automatically placed at the first (i.e, In case of sorting in ascending order, smallest element will be at first and in case of sorting in descending order, largest element will be at first.). Similarly, in third step, comparison starts from third element and so on.

C Program to Sort Elements Using Selection Sort Algorithm

#include <stdio.h>
int main()
 {
    int data[100],i,n,steps,temp;
    printf("Enter the number of elements to be sorted: ");
    scanf("%d",&n);
    for(i=0;i<n;++i)
      {
       printf("%d. Enter element: ",i+1);
       scanf("%d",&data[i]);
    }
    for(steps=0;steps<n;++steps)
    for(i=steps+1;i<n;++i)
     {
         if(data[steps]>data[i])  
/* To sort in descending order, change > to <. */
          {
             temp=data[steps];
             data[steps]=data[i]; 
             data[i]=temp;
         }
    }
    printf("In ascending 
    for(i=0;i<n;++i)
   
Output
Enter the number of elements to be sorted: 5
1. Enter element: 12
2. Enter element: 1
3. Enter element: 23
4. Enter element: 2
5. Enter element: 0
In ascending order: 0 1 2 12 23
Note: Though this program is in C, selection sort algorithm can be similarly used in other programming language as well.
Selection sort algorithm is easy to use but, there are other sorting algorithm which perform better than selection sort. Specially, selection sort shouldn't be used to sort large number of elements if the performance matters in that program.

Merge Sort Algorithm

Merge Sort is a kind of Divide and Conquer algorithm in computer programrming. It is one of the most popular sorting algorithms and a great way to develop confidence in building recursive algorithms.

Divide and Conquer Strategy

Using the Divide and Conquer technique, we divide a problem into subproblems. When the solution to each subproblem is ready, we 'combine' the results from the subproblems to solve the main problem.
Suppose we had to sort an array A. A subproblem would be to sort a sub-section of this array starting at index p and ending at index r, denoted as A[p..r].
Divide
 
If q is the half-way point between p and r, then we can split the subarray A[p..r] into two arrays A[p..q] and A[q+1, r].
 
Conquer
 
In the conquer step, we try to sort both the subarrays A[p..q] and A[q+1, r]. If we haven't yet reached the base case, we again divide both these subarrays and try to sort them.
 
Combine
 
When the conquer step reaches the base step and we get two sorted subarrays A[p..q] and A[q+1, r] for array A[p..r], we combine the results by creating a sorted array A[p..r] from two sorted subarrays A[p..q] and A[q+1, r]
 

The MergeSort Algorithm

The MergeSort function repeatedly divides the array into two halves until we reach a stage where we try to perform MergeSort on a subarray of size 1 i.e. p == r.
 
After that, the merge function comes into play and combines the sorted arrays into larger arrays until the whole array is merged.
MergeSort(A, p, r)
    If p > r 
        return;
    q = (p+r)/2;
    mergeSort(A, p, q)
    mergeSort(A, q+1, r)
    merge(A, p, q, r)
To sort an entire array, we need to call MergeSort(A, 0, length(A)-1).

The merge step of merge sort

Every recursive algorithm is dependent on a base case and the ability to combine the results from base cases. Merge sort is no different. The most important part of the merge sort algorithm is, you guessed it, the "merge" step.
The merge step is the solution to the simple problem of merging two sorted lists(arrays) to build one large sorted list(array).
The algorithm maintains three pointers, one for each of the two arrays and one for maintaining the current index of final sorted array.
Have we reached the end of any of the arrays?
    No:
        Compare current elements of both arrays 
        Copy smaller element into sorted array
        Move pointer of element containing smaller element
    Yes:
        Copy all remaining elements of non-empty array

Writing the code for merge algorithm

A noticeable difference between the merging step we described above and the one we use for merge sort is that we only perform the merge function on consecutive sub-arrays.
This is why we only need the array, the first position, the last index of the first subarray(we can calculate the first index of second subarray) and the last index of second subarray.
Our task is to merge two subarrays A[p..q] and A[q+1..r] to create a sorted array A[p..r]. So the inputs to the function are A, p, q and r
The merge function works as follows:
  1. Create copies of the subarrays L ← A[p..q] and M ← A[q+1..r].
  2. Create three pointers i,j and k
    1. i maintains current index of L, starting at 1
    2. j maintains current index of M, starting at 1
    3. k maintains current index of A[p..q], starting at p
  3. Until we reach the end of either L or M, pick the larger among the elements from L and M and place them in the correct position at A[p..q]
  4. When we run out of elements in either L or M, pick up the remaining elements and put in A[p..q]
In code, this would look like:
void merge(int A[], int p, int q, int r)
{
    /* Create L ← A[p..q] and M ← A[q+1..r] */
    int n1 = q - p + 1;
    int n2 =  r - q;
 
    int L[n1], M[n2];

    for (i = 0; i < n1; i++)
        L[i] = A[p + i];
    for (j = 0; j < n2; j++)
        M[j] = A[q + 1 + j];
    
    /* Maintain current index of sub-arrays and main array */
    int i, j, k;
    i = 0; 
    j = 0; 
    k = p; 


    /* Until we reach either end of either L or M, pick larger among elements L and M and place them in the correct position at A[p..r] */
    while (i < n1 && j < n2)
    {
        if (L[i] <= M[j])
        {
            arr[k] = L[i];
            i++;
        }
        else
        {
            arr[k] = M[j];
            j++;
        }
        k++;
    }
 
    /* When we run out of elements in either L or M, pick up the remaining elements and put in A[p..r] */
    while (i < n1)
    {
        A[k] = L[i];
        i++;
        k++;
    }
 
    while (j < n2)
    {
        A[k] = M[j];
        j++;
        k++;
    }
}


Comments

Post a Comment

Popular posts from this blog

Forget Efficiency and start solving easier problems

Good schedule to follow for becoming better at competitive programming for beginners

New practice session for all the programmers with me.