Insertion Sort
- The basic idea of this method is to insert an unsorted element in it's correct position in a sorted set of element.
- Insertion sort is simple sorting algorithm that works similar to the way you sort playing cards in your hand.
- Advantages of Insertion Sort
- It is a simple sorting method.
- No additional data structure is required.
- It is stable sorting method.
- Best case time complexity is Ω (n).
- It also exhibits good performance when deling with a small list.
- Disadvantages of Insertion Sort
- It does not perform as well as other, better sorting algorithm.
- The insertion sort does not deal well with a huge list.
- The insertion sort is particularly useful only when sorting a list of few items.
- worst case time complexity is O(n2).
⊚Complexity of Insertion Sort
- Time Complexity
- Best Case: Ω (n)
- Woest Case: O(n2)
- Space Comlplexity
- Worst Case: O(1)
- Stable: YES
CODE
👇
- #include<stdio.h>
- int comp_cnt;
- void main()
- {
- int a[20], i, n;
- void insertion(int a[], int n);
- printf("How many elements you want to enter ? \n");
- scanf("%d", &n);
- printf("Enter %d elements \t", n);
- for(i=0; i<n; i++)
- {
- scanf("%d", &a[i]);
- }
- insertion(a,n);
- printf("Sorted elements are \t");
- for(i=0; i<n; i++)
- {
- printf("%d\t", a[i]);
- }
- printf("\n Total number of comparisions %d \n", comp_cnt);
- }
- void insertion(int a[20], int n)
- {
- int i, k, new;
- for(k=1; k<n; k++)
- {
- new=a[k];
- for(i=k-1; i>=0; i--)
- {
- comp_cnt++;
- if(a[i]>new)
- {
- a[i+1]=a[i];
- }//if
- else
- break;
- }inner for
- a[i+1]=n
- }//outer for
- }//insertion function
👉Execute👈
//Output
/*
How many elements you want to enter ?
5
Enter 5 elements 6
5
1
8
3
Sorted elements are 1 3 5 6 8
Total number of comparisions 8
*/
//ThE ProFessoR
Comments
Post a Comment