A little help with insertion sort
Jul 3, 2014 at 10:47pm UTC
Hello! Could someone please point out the mistake in my code? This is insertion sort and even though i checked the code thoroughly, it does not sort appropriately. Thank You!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <stdio.h>
#include <stdlib.h>
main()
{
int n = 0, key = 0, i = 1, j = 2;
printf("n = " ); scanf("%d" , &n);
int *arr = calloc(n, sizeof (int ));
for (int i = 1; i <= n; i++)
{ printf("a[%d] = " , i); scanf("%d" , &arr[i]); printf("\n" ); }
while (j <= n) {
key = arr[j];
i = j - 1;
while (i > 0 && arr[i] > key)
{
arr[i+1] == arr[i];
i--;
}
arr[i+1] = key;
j++;
}
for (int i = 1; i <= n; i++) printf("%d " , arr[i]);
printf("\n" );
free(arr);
}
Jul 3, 2014 at 11:04pm UTC
line 19: statement has no effect
You also have out of bounds access. Remember that valid index are from 0 to size-1
Jul 4, 2014 at 9:27am UTC
Thank you! I need to pay more attention next time!
Topic archived. No new replies allowed.