c++ - 这是插入排序吗?

标签 c++ algorithm insertion-sort

<分区>

我正在阅读“算法导论”并了解插入排序。
我尝试在没有先阅读他们的解决方案的情况下自己实现它。

这是我的解决方案,这是插入排序吗?

#include <iostream>

using namespace std;

int main()
{
    // initialize an unsorted array
    int a[] = {5,6,4,7,3,8,2,9,0,1};

    // define variables
    int i,j,tmp;

    for (int j=1; j<10; ++j)
    {
        for (int i=0;i<j;++i)
        {
            if (a[j] < a[i])
            {
                tmp = a[j];
                a[j] = a[i];
                a[i] = tmp;
            }
        }

    }

    for (i=0;i<10;++i)
    {
        cout << a[i] << endl;
    }

    return 0;
}

好的,我已经读过了,明白为什么它不是插入排序了……这样好多了。

   #include <iostream>

    using namespace std;

    int main()
    {
        // initialize an unsorted array
        int a[] = {5,6,4,7,3,8,2,9,0,1};

        // define variables
        int i,j,key,c;

        for (int j=1; j<10; ++j)
        {
            key = a[j];
            i = j - 1;

            while(i>=0 && a[i] > key)
            {
                a[i+1] = a[i];
                i = i - 1;
            }
            a[i+1] 

= key;
        ++c;
    }

    for (i=0;i<10;++i)
    {
        cout << a[i] << endl;
    }

    cout << endl << c << endl;
    return 0;
}

最佳答案

您的解决方案似乎是冒泡排序,而不是插入排序。

关于c++ - 这是插入排序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6439490/

相关文章:

algorithm - 使用动态规划将自然数表示为平方和

c - C中双向链表的插入排序

python - 构造插入排序

c++ - MEX:如何将矩阵从 C++/C 返回到 MATLAB

c++ - AIX 服务器中的 g++ 编译 - 抛出核心转储

algorithm - 运行时间(空 for 循环与一条语句的 for 循环)

c - 在输入值的同时对数组进行排序

android - OpenGL 3.0 ES 中的错误纹理渲染

c++ - 关于我在 C++ 代码中从未见过的特殊运算符的一些问题

c# - 力扣 : Prison Cells After N Days