Skip to content

šŸ§¬Insertion Sort : inserting happiness in my lifešŸ¤“

Notifications You must be signed in to change notification settings

Abhishek-Singh296/Insertion-Sort

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Ā 

History

6 Commits
Ā 
Ā 
Ā 
Ā 

Repository files navigation

Insertion-Sort

Insertion sort is an algorithm used to sort a collection of elements in ascending or descending order. The basic idea behind the algorithm is to divide the list into two parts: a sorted part and an unsorted part.Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration.


Working

Suppose we need to sort the following array.

Frame 4_0

1.The first element in the array is assumed to be sorted. Take the second element and store it separately in key.Compare key with the first element. If the first element is greater than key, then key is placed in front of the first element.

Insertion-sort-0_1

2.Now, the first two elements are sorted.Take the third element and compare it with the elements on the left of it. Placed it just behind the element smaller than it. If there is no element smaller than it, then place it at the beginning of the array.

Insertion-sort-1_1

3.Similarly, place every unsorted element at its correct position.

Insertion-sort-2_2

Insertion-sort-3_2


Algorithm

To sort an array of size N in ascending order:

  • Iterate from arr[1] to arr[N] over the array.
  • Compare the current element (key) to its predecessor.
  • If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.

Code

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int InsertionSort(int a[], int array_size)
{
	int i,j,small;
	for(i=1;i<array_size;i++)
	{
		small=a[i];
		for(j=i-1;j>=0 && small<a[j];j--)
		{
				a[j+1]=a[j];
		
		}
		a[j+1]=small;
	}
	 printf("\nSorted Data :");
    for (i = 0; i < array_size; i++) {
        printf("\t%d", a[i]);
}
}
int main()
{
  int ret,element;
  int arr[5]={32,5,7,3,72};
  InsertionSort(arr,5);
  if(ret==-1)
  {
   printf("Element not found!");
  }
  
}

Output

Screenshot 2023-04-24 015641


About

šŸ§¬Insertion Sort : inserting happiness in my lifešŸ¤“

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages