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

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -