Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
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 10:10am
Edited 18-Feb-13 10:11am
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

 #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  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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
0 DamithSL 305
1 OriginalGriff 275
2 Sergey Alexandrovich Kryukov 207
3 Peter Leow 185
4 Afzaal Ahmad Zeeshan 154
0 OriginalGriff 7,460
1 DamithSL 5,519
2 Sergey Alexandrovich Kryukov 4,954
3 Maciej Los 4,936
4 Kornfeld Eliyahu Peter 4,514


Advertise | Privacy | Mobile
Web02 | 2.8.141223.1 | Last Updated 18 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100