Skip to main content

Insertion Sort

Insertion Sort is a simple sorting algorithm. It is like picking up an element from the list and inserting it to its rightful index as per intendent order of the elements in the list. Initially, the first element is considered to be at its right place and as we go through the elements of the list, the sorting takes place by comparing the elements.

Illustration:

Algorithm:

for all elements in list,step=from step=0 to step=length(list)-1
    first element is sorted,when step=0
    key=list[step],the element to be extracted to insert at the right index
    j=step-1
    while j>=0 and key < value at index j
        list[j+1]=list[j]
        j=j-1
    list[j+1]=key

Time Complexity:
  • Worst Case: O(n2)
  • Average Case: O(n2)
  • Best Case: O(n)
Space Complexity: O(1)

Program for insertion sort:


Output:

Comments

Popular posts from this blog

Coding Problem: Sober Walk

Our hoary culture had several great persons since time immemorial and king vikramaditya’s nava ratnas(nine gems) belongs to this ilk. They are named in the following shloka: Among these, Varahamihira was an astrologer of eminence and his book Brihat Jataak is recokened as the ultimate authority in astrology. He was once talking with Amarasimha,another gem among the nava ratnas and the author of Sanskrit thesaurus, Amarakosha. Amarasimha wanted to know the final position of a person, who starts from the origin 0 0 and travels per following scheme.     He first turns and travels 10 units of distance     His second turn is upward for 20 units     Third turn is to the left for 30 units     Fourth turn is the downward for 40 units     Fifth turn is to the right(again) for 50 units … And thus he travels, every time increasing the travel distance by 10 units. Code:

Image to Pencil Sketch using Python and OpenCV

In this post, we will go through a program to get a pencil sketch from an image using python and OpenCV.  Step 1:  To use OpenCV, import the library. Step 2: Read the Image. Step 3: Create a new image by converting the original image to grayscale. Step 4: Invert the grayscale image. We can invert images simply by subtracting from 255, as grayscale images are 8 bit images or have a maximum of 256 tones. Step 5: Blur the inverted image using GaussianBlur  method in OpenCV library and invert the blurred image.  Step 6: Divide the grayscale values of the image by the values of image received from step-5 ( Note: We inverted the grayscale image and we blurred this image and then again inverted it ). Diving an image from its smoothened form will highlight the edges and we get the image like Pencil Sketch. Steps Illustration: Code: Execution Output: