Insertion Sort - Show passes with no of camparison and swap
On-campus and online computer science courses to Learn the basic concepts of Computer Science.This tutorial will cover c ,c++, java, data structure and algorithm,computer graphics,microprocessor,analysis of algorithms,Digital Logic Design and Analysis,computer architecture,computer networks,operating system.
Insertion Sort code in C:
#include<stdio.h> int a[100],count=0,swap=0,k; int check(int j,int temp) { if( temp<a[j]&&j>=0 ) // shift while loop condition to check function { //for comparison count count++; return 1; } else { count++; return 0; } } int main() { int i,j,n,temp; printf("Enter total elements: "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter number :"); scanf("%d",&a[i]); } for(i=1;i<n;i++) { temp=a[i]; j=i-1; while( check(j,temp) ) { a[j+1]=a[j]; j=j-1; swap++; } a[j+1]=temp; count++; printf("\npass %d:\t",i+1); for ( k = 0 ; k < n ; k++ ) printf("%d\t", a[k]); } printf("\nAfter sorting: "); for(i=0;i<n;i++) printf(" %d",a[i]); printf("\ncomparison count %d",count); printf("\nswap count %d",swap); // shift copy count return 0; }output:-
Enter total elements: 5 Enter number :29 Enter number :21 Enter number :64 Enter number :20 Enter number :56 pass 2: 21 29 64 20 56 pass 3: 21 29 64 20 56 pass 4: 20 21 29 64 56 pass 5: 20 21 29 56 64 After sorting: 20 21 29 56 64 comparison count 13 swap count 5 --------------------------------
0 comments: