public static void insertionSort(int[] array) {
for (int i = 1; i < array.length; i ) {
int key = array[i];
while (i > 0 && key < array[i-1]) {
array[i--] = array[i-1];
}
array[i] = key;
}
I got this piece of code and don't really understand how the array[i--]
part works. Based on my understanding, i--
changes the value of i
after the statement is ran while --i
changed the value of i
after expression. However, in this case, array[i--]
is not the same as array[i]
and put the i--
part under the statement. Can everyone explain? Doesn't this means that array[i--]
in this case is the same as array[--i]
?
CodePudding user response:
Learn about pre
and post
increment operator.
Try to avoid such type of statement, because it decreases code readability
int a=5,b;
b = a; //equivalent to: a = a 1; b = a;
System.out.println(b " - " a); // 6 - 6
a = 6;
b = a ; //equivalent to: b = a; a = a 1
System.out.println(a " - " b); // 7 6
int[] arr = {1,2,3,4};
int i=3;
while(i!=0){
System.out.println(arr[i--]); // 4 3 2
// --- equivalent to below two statments: ---
// System.out.println(arr[i]);
// i = i-1;
}
CodePudding user response:
array[i--] = array[i-1];
is same as
array[i] = array[i - 1 - 1];
i = i - 1; // or: i -= 1; or: i--; or: --i;
The post decrement i--
will happen directly after reading the value of i
and not after finishing the complete statement.