Insertion Sort

    by nikoo28

    Insertion sort is the most generic example of a sorting algorithm, and the one which is used by one of the most naive users. Often we must have also used this algorithm in our real life examples unknowingly. One of the favorite example is:-

    example showing insertion sort
    Sorting a hand of cards

    This is a very common scenario and we must have used it. Suppose you get a hand of cards. Our general approach is that we start scanning the cards from starting and if we find a card out of place, we remove it from there and start looking from the beginning and insert it at the right place.

    STEPS:

    Suppose our cards are arranged like 2, 4, 6, 3, 10, K, J. The steps we follow would be:-

    • Start scanning the cards. 2 is correct, 4 is correct, 6 is correct. 3 is NOT correct. It does not follow the ascending order.
    • Now we need to insert 3 at the right place.
    • Pick up card 3 and start scanning from the beginning. 3 is greater than 2, so move ahead. 3 is less than 4, so INSERT the card 3 before 4. Now our hand is 2, 3, 4, 6, 10, K, J.
    • Now again start scanning the cards from where we left off. 6 is at right place, 10 is at right place, K is at right place. J is not at right place, because it is not following the ascending order rule.
    • Pick up card J and start scanning form the beginning. J is greater than 2, 3, 4, 6, 10. But J is less than K, so INSERT the card J before K.

    Now our sorting is finally complete and thus, the hand we have is:- 2, 3, 4, 6, 10, J, K. We INSERTED the cards in the middle and hence this type of sorting gets its name INSERTION SORT.

    ALGORITHM:

    Now we can devise an algorithm for this sorting technique.

    1. Start scanning the elements from 2nd position. The 1st is assumed to be at correct place.
    2. if ( arr[i] < arr[i-1])
      • Swap arr[i] and arr[i-1]
      • Keep swapping until the number is less than the previous number
    3. The array gets sorted as we reach the end.

    Here is a working implementation of the same.

    #include<stdio.h>;
    
    // function to swap two integers
    void swap(int *x, int *y)
    {
        int temp = *x;
        *x = *y;
        *y = temp;
    }
    
    // a function to perform Insertion Sort on the array arr with size specified
    void insertionSort(int arr[],int size)
    {
        int i,j;
    
        // iterating from 2nd element to the last
        for(i = 1; i < size; i++)
        {
            if(arr[i] < arr[i-1])
            {
                j = i;
                while(arr[j-1] < arr[j])
                {
                    // swapping all the numbers
                    // until the next number is smaller than previous number
                    swap(&arr[j], &arr[j-1]);
                    j--;
                }
            }
        }
    }
    
    // driver function to test the above function
    int main(void)
    {
        int i;
        int arr[10] = {3, 4, 7, 1, 10, 8, 2, 22, 99, 50};
    
        insertionSort(arr,10);
    
        printf("SORTED array:- ");
        for(i = 0; i < 10; i++)
            printf("%d ",arr[i]);
    
        return 0;
    }
    Code language: C/AL (cal)

    Running Time:-
    Average Case:- O(n2)
    Best Case:- O(n)
    Worst Case:- O(n2)

    Video Explanation:

    YouTube player
    0 comments
    0 FacebookTwitterLinkedinWhatsappEmail
  • ArraysTheory

    SORTING and its types

    by nikoo28
    5 minutes read

    What is sorting? Sorting is an algorithm that arranges the elements of a list in a certain order (either ascending or descending, as per the requirement). The output is simply a permutation of the input data. Why sorting? Sorting is one of the most important categories of algorithms in computer science. Sometimes sorting significantly reduces the problem complexity. We can use sorting as a technique to reduce the search complexity. Great research went into this category of algorithms because of its importance. These algorithms are very much used in many …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Misc

    Write a program to calculate pow(x,n)

    by nikoo28
    3 minutes read

    We will discuss how to calculate the result when a number ‘x’ is raised to the power ‘y’. Originally C provides a standard function that allows us to directly use the power function. It can be used in the following manner. Now suppose that we need to write a custom function by ourselves. Here are the sample methods by which we can do so. Simple Iterative method Recursive Method But in both these methods, the time complexity is of O(n), and this can take a long time in operation. We …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Theory

    What is a priority queue?

    by nikoo28
    2 minutes read

    In some situations we might need to find the minimum/maximum element among a collection of elements. Priority Queue ADT is the one which supports these kind of operations. A priority queue ADT is a data structure that supports the operations Insert and DeleteMin (which returns and removes the minimum element) or DeleteMax (which returns and removes the maximum element). These operations are equivalent to EnQueue and DeQueue operations of a queue. The difference is that, in priority queues, the order in which the elements enter the queue may not be …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Theory

    How do pointers to pointers work in C?

    by nikoo28
    3 minutes read

    We generally see cases like:-Here ptr is a pointer to a memory location of the variable x. What if we do something likeWhat we did just now was made a pointer to a pointer. Now the question arises, what happens behind the scene? Let’s assume an 8 bit computer with 8 bit addresses (and thus only 256 bytes of memory). This is part of that memory (the numbers at the top are the addresses): What we can see here, is that at address 63 the string “hello” starts. So in …

    0 FacebookTwitterLinkedinWhatsappEmail

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More