12,881,367 members (28,136 online)
Rate this:
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
Updated 18-Feb-13 9:11am
v2

Rate this:

## 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:

## 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:

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

Top Experts
Last 24hrsThis month
 OriginalGriff 148 ppolymorphe 110 bling 95 Karthik Bangalore 40 Menon Santosh 35
 OriginalGriff 3,532 Karthik Bangalore 2,391 CHill60 2,358 Jochen Arndt 1,998 ppolymorphe 1,780