小编use*_*507的帖子

插入排序算法忽略第一个元素

我正在用 C++ 实现一个简单的插入排序,如下所示:

void insertion_sort(int a[], int size)
{
    int temp;
    for (int i = 2; i < size; i++)
    {
        temp = a[i];
        int j = i - 1;
        while (j > 0 && a[j] > temp)
        {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = temp;
        print_array(a, size);
    }
    cout << "Final:" << endl;
    print_array(a, size);
}
Run Code Online (Sandbox Code Playgroud)

但是,这会对数组中除第一个元素之外的所有元素进行排序。这是输出的样子:

Original array:
5 2 4 1 3 0 
Insertion Sorted array:
5 2 4 1 3 0 …
Run Code Online (Sandbox Code Playgroud)

c++ sorting algorithm insertion-sort

2
推荐指数
1
解决办法
1697
查看次数

标签 统计

algorithm ×1

c++ ×1

insertion-sort ×1

sorting ×1