i created one insertion sort code using nested for. just because I'm writing condition in if part separately inside for loop, it gives me different answers. please tell me what's wrong with my approach.
i tried searching online but i did not get the result this is my code:
#include <stdio.h>
int main() {
int i, j;
int arr[] = {32, 5, 45, 8, 17, 82, 10};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Before Sorting: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
for (i = 1; i < size; i++) {
int key = arr[i];
for (j = i - 1; j >= 0; j--)
{
if(arr[j] > key)
arr[j + 1] = arr[j];
}
arr[j + 1] = key;
}
printf("\nAfter Sorting: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
The problem with the nested for loops
is that
arr[0]is always set tokeybecause after the inner for loopjis equal to-1.You could rewrite them for example like
Pay attention to that the type of the value produced by the operator sizeof has type
size_t. So it will be more correctly to writeAlso you should declare variables in minimum scopes where they are used.
I would write the program the following way