Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
Node is saved as draft in My Content >> Draft
  • Insertion sort in C

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 56
    Comment on it

    Sorting in C is mainly done to arrange elements either in ascending or in descending order.

     

    Sorting in done in programming by various ways

     

    We are about to discuss insertion sort that will take element wise comparison for performing sorting.

     

    Working of Insertion sort algorithm in programming to sort elements of an array.

     

    In the given figure it is clearly understood that first element is compared with the second one and swapping is done  in the first iteration.

     

    After this in the second iteration first element is compared with second and then third element and swapping is done whichever is lower will comes in the first position.

     

    /*Sorting Elements of an array in ascending order using insertion sort algorithm*/
    #include<stdio.h>
    int main()
    {
    	int data[100],n,temp,i,j;
    	printf("Enter number of terms(should be less than 100): ");
    	scanf("%d",&n);
    	printf("Enter elements: ");
    	for(i=0;i<n;i++)
    	{
    		scanf("%d",&data[i]);
    	}
    	for(i=1;i<n;i++)
    	{
    		temp = data[i];
    		j=i-1;
    		while(temp<data[j] && j>=0)
    /*To sort elements in descending order, change temp<data[j] to temp>data[j] in above line.*/
    		{
    			data[j+1] = data[j];
    			--j;
    		}
    		data[j+1]=temp;
    	}
    	printf("In ascending order: ");
    	for(i=0; i<n; i++)
    		printf("%d\t",data[i]);
        return 0;
    }

     

    .net

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: