This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
我正在读“算法简介”和关于插入排序的文章我试着自己实现它,而没有先阅读他们的解决方案。
这是我的解决方案,这是插入式的吗?

#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/

10-12 01:35
查看更多