int[] array = { 4, 7, 1, 5, 2, 6 };
for (int i = 0; i < array.length; i++)
{
for (int j = i; j > 0 && array[j - 1] > array[j]; j--)
{
array[j] = array[j - 1] + array[j];
array[j - 1] = array[j] - array[j - 1];
array[j] = array[j] - array[j - 1];
}
}
Insertion sort, the above exchange does not use intermediate variables, but there is also a problem, there may be overflow, because a=a+b may cause overflow, another way without intermediate variables is to use XOR: a= a^b,b=a^b,a=a^b This method is not suitable for floating point numbers. In short, it is just used to exchange data without any additional space. . . The focus is still on the algorithm itself. .
Nested loop is a way of writing insertion sort, but the inner loop body is different from insertion sort.
Insertion sort, the second level of loop is if array[j-1]>array[j], exchange the values of array[j] and array[j-1]
Insertion sort
This code means exchange, no intermediate variables are needed
Insertion sort. The inside of the second level loop means exchanging values
Insertion sort, the code in the second level loop may look a bit messy, but if simplified it is equivalent to:
a = a – b;
* means the exchange of values of a and b. If you don’t understand, you can substitute the specific numbers to see.