Click here to Skip to main content
Sign Up to vote bad
good
See more: C
I have faced a problem in C with insertion sort. Can you please explain it with the proper code and algorithm?
Posted 18 Feb '13 - 9:10
Edited 18 Feb '13 - 9:11
richcb12.6K


3 solutions

 #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..
  Permalink  
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.
  Permalink  
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.
  Permalink  

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 483
1 Arun Vasu 315
2 OriginalGriff 250
3 Maciej Los 218
4 Aarti Meswania 170
0 Sergey Alexandrovich Kryukov 9,670
1 OriginalGriff 7,409
2 CPallini 3,968
3 Rohan Leuva 3,352
4 Maciej Los 2,861


Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 18 Feb 2013
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid