12,358,339 members (68,274 online)
Rate this:
Please Sign up or sign in to vote.
See more:
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:10am
Edited 18-Feb-13 9:11am
v2

## 3 solutions

Rate this:
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..
v3
Rate this:
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.
Rate this:
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.

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

Top Experts
Last 24hrsThis month
 OriginalGriff 270 Jochen Arndt 260 Sergey Alexandrovich Kryukov 210 Richard Deeming 205 Prava-MFS 205
 OriginalGriff 10,228 Dave Kreskowiak 3,384 ppolymorphe 2,507 Karthik Bangalore 2,411 Richard MacCutchan 2,369

Advertise | Privacy | Mobile
Web01 | 2.8.160621.1 | Last Updated 18 Feb 2013
Copyright © CodeProject, 1999-2016
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