C- Insertion sort -
what's wrong code? while loop part doesn't work. if statement not enough terminate while loop
int main(void) { int data[size] = { 12,2,5,8,2,45,89,0,12,4 }; int i, j, tmp; (i = 0; < size-1; i++) { j = + 1; tmp = data[j]; while (j > 0){ if(data[j-1] > tmp){ data[j] = data[j - 1]; j--; } } data[j] = tmp; } (i = 0; < size; i++) printf("%d, ", data[i]); return 0; }
j--;
inside if
statement. if data[j-1] > tmp
false
loop not terminate. apart algorithm not sort array. adapt code this:
int main (void) { int data[size] = { 12,2,5,8,2,45,89,0,12,4 }; int i, j, tmp; (i = 0 ; < size - 1; i++) { j = i+1; while ( j > 0 && data[j] < data[j-1]) { tmp = data[j]; data[j] = data[j-1]; data[j-1] = tmp; j--; } } (i = 0; < size; i++) { printf("%d, ", data[i]); } return 0; }
Comments
Post a Comment