Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have faced a problem in C with insertion sort. Can you please explain it with the proper code and algorithm?
Posted
Updated 18-Feb-13 9:11am
v2

C#
 #include<stdio.h>
int main(){

  int i,j,s,temp,a[20];

  printf("Enter total elements: ");
  scanf("%d",&s);

  printf("Enter %d elements: ",s);
  for(i=0;i<s;i++)>
      scanf("%d",&a[i]);

  for(i=1;i<s;i++){>
      temp=a[i];
      j=i-1;
      while((temp<a[j])&&(j>=0)){
      a[j+1]=a[j];
          j=j-1;
      }
      a[j+1]=temp;
  }

  printf("After sorting: ");
  for(i=0;i<s;i++)>
      printf(" %d",a[i]);

  return 0;
}

Output:
Enter total elements: 5
Enter 5 elements: 3 7 9 0 2
After sorting:  0 2 3 7 9</stdio.h>


This program will replace first element to the target place in each iteration according to ascending or descending orders..
 
Share this answer
 
v3
Well, the first hit at google for "Insertion sort C++" gave this[^], which looks good to me.

Google is a powerful tool. It is your friend. You should embrace it and learn to use it.
 
Share this answer
 
Not as well as a very quick Google would have done: Google "Insertion sort"[^]
The first hit is Wikipedia with both a good explanation and a code sample, in C: Wikipedia "Insertion_sort"[^]

In future, please try to do at least basic research yourself, and not waste our time or yours.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900