Ticker

6/recent/ticker-posts

Insertion Sort- DSA C Program


 This is the Insertion Sort program in C for sorting the array in ascending order.

#include<stdio.h>
	int main()
	{
	    int k, a[10], n, i, j, key;
	    printf("enter the no of elements you want to add : ");
	    scanf("%d",&n);
	    printf("enter the array elements : ");
	    for(i=0; i<n; i++)
	    {
	        scanf("%d",&a[i]);
	    } 
	printf("sorted array : ");
	
	for(i=1;i<n;i++){
		key=a[i];
		j=i-1;
		while(j>=0 && a[j]>key){
			a[j+1]=a[j];
			j=j-1;
		}
		a[j+1]=key; // as now j=j-1 so now a[j+1-1]=a[j] 
		}
		for(i=0;i<n;i++){
		printf("%d  ",a[i]);
	}
	}

Post a Comment

0 Comments