0

see the message

for ( int i = 1; i < n ; i++){ int temp = arr[i]; int j; for ( j = i-1 ; j >= 0 ; j-- ){ if ( arr[j] > temp){ arr[ j+1 ] = arr[j]; } else { break; } } arr[j+1] = temp; } why can't we use if ( arr[j] > arr[i] ) in place of if ( arr[j] > temp )

2nd Jul 2022, 9:06 PM
blueshipswims
blueshipswims - avatar
1 Odpowiedź
+ 4
Because in the second for loop, arr[i] can change its value (note that arr[j+1] is equal to arr[i] at the first iteration) . If arr[i] is changed then the second for loop wont work properly.
2nd Jul 2022, 9:26 PM
Black Winter