java - 请问描述中的排序叫什么名字。
PHPz
PHPz 2017-04-17 17:27:35
0
6
455
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];
    }
}
PHPz
PHPz

学习是最好的投资!

reply all(6)
黄舟

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

array[j] = array[j - 1] + array[j];
array[j - 1] = array[j] - array[j - 1];
array[j] = array[j] - array[j - 1];

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;
b = a – b;

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template