Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 这是插入式排序吗?_C++_Algorithm_Insertion Sort - Fatal编程技术网

C++ 这是插入式排序吗?

C++ 这是插入式排序吗?,c++,algorithm,insertion-sort,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 (

我正在阅读“算法简介”并阅读有关插入排序的内容
我试图自己实现它,而没有先阅读他们的解决方案

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

#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;
}
#包括
使用名称空间std;
int main()
{
//初始化未排序的数组
int a[]={5,6,4,7,3,8,2,9,0,1};
//定义变量
int i,j,tmp;

对于(int j=1;j您的解决方案似乎是冒泡排序,而不是插入排序。

在我看来,它类似于插入排序。您正在一次创建一个排序数组(
a[0…j]


您的插入异常且效率低下。若要将
a[j]
插入
a[0…j]
中,您不需要将其与每个元素进行比较。

为什么要问我们?请阅读他们的解决方案,然后进行比较。*密钥已修复,应该是tmp。谢谢您的帮助。好的,这正是我所担心的。
   #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;
}