Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

BALAJI CHETTIAR 122A1021 Div: C

Experiment 1(B)

Aim: Implement Insertion Sort and find out time complexity.

Algorithm for sorting numbers in ascending order

Step 1 - If the element is the first element, assume that it is already sorted. Return 1.

Step2 - Pick the next element, and store it separately in a key.

Step3 - Now, compare the key with all elements in the sorted array.

Step 4 - If the element in the sorted array is smaller than the current element, then
move to the next element. Else, shift greater elements in the array towards the right.

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.

Code:

#include<stdio.h>
int main()
{
int a[25];int n;
printf("Enter total no. of elements: ");
scanf("%d", &n);
printf("Enter the numbers one by one\n");
for (int i = 0; i < n; ++i){
scanf("%d", &a[i]);
}

int i,j,key;
for(j=1;j<n;j++)
{
key=a[j];
i=j-1;
while(i>=0 && a[i]>key)
{
a[i+1]=a[i];
i--;
}
a[i+1]=key;
}
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
return 0;
}

Output:

Conclusion: Time Complexity : Average and Worst case -O(n2)

Best case-O(1)

Space Complexity: O(1)

You might also like