C++ 为什么我的插入排序没有得到第一个元素?

C++ 为什么我的插入排序没有得到第一个元素?,c++,arrays,sorting,C++,Arrays,Sorting,我的插入排序对除第一个数字以外的所有数字进行排序。它从第二个元素排序到最后一个元素,但从不包括第一个元素。我的插入排序有什么问题。我根据CLRS一书中的伪代码编写了这段代码,我无法调试它的错误 #include <iostream> void InsertSort(int data[], int length) { //std::cout<<length<<std::endl; for(int j = 1; j < length; j++

我的插入排序对除第一个数字以外的所有数字进行排序。它从第二个元素排序到最后一个元素,但从不包括第一个元素。我的插入排序有什么问题。我根据CLRS一书中的伪代码编写了这段代码,我无法调试它的错误

#include <iostream>
void InsertSort(int data[], int length)
{
    //std::cout<<length<<std::endl;
    for(int j = 1; j < length; j++)
    {
        int key = data[j];
        int i = j - 1;
        while(i > 0 && data[i] > key)
        {
            data[i + 1] = data[i];
            i--;
        }
        data[i+1] = key;
    }
    for(int x = 0; x < length; x++)
    {
        std::cout<<data[x]<<" ";
    }
    std::cout<<std::endl;
}


int main(int argc, const char * argv[])
{
    // insert code here...
    //std::cout << "Hello, World!\n";

    int foo [] = { 18, 2, 77, 0, 12071 , 21, 45, 98, 54, 80};
    InsertSort(foo, 10);


    return 0;
}
如果存在复制正确的问题,我将删除伪代码


正如您所看到的,我的第一个元素没有被排序,并且由于某种原因从未被排序。我的代码有什么问题?

将while循环更改为

while(i >= 0 && data[i] > key)
以下是更新的代码:

#include <iostream>
void InsertSort(int data[], int length)
{
    //std::cout<<length<<std::endl;
    for(int j = 1; j < length; j++)
    {
        int key = data[j];
        int i = j - 1;
        while(i >= 0 && data[i] > key)
        {
            data[i + 1] = data[i];
            i--;
        }
        data[i+1] = key;
    }
    for(int x = 0; x < length; x++)
    {
        std::cout<<data[x]<<" ";
    }
    std::cout<<std::endl;
}


int main(int argc, const char * argv[])
{
    // insert code here...
    //std::cout << "Hello, World!\n";

    int foo [] = { 18, 2, 77, 0, 12071 , 21, 45, 98, 54, 80};
    InsertSort(foo, 10);


    return 0;
}
#包括
void InsertSort(int数据[],int长度)
{

//std::cout将while循环更改为

while(i >= 0 && data[i] > key)
以下是更新的代码:

#include <iostream>
void InsertSort(int data[], int length)
{
    //std::cout<<length<<std::endl;
    for(int j = 1; j < length; j++)
    {
        int key = data[j];
        int i = j - 1;
        while(i >= 0 && data[i] > key)
        {
            data[i + 1] = data[i];
            i--;
        }
        data[i+1] = key;
    }
    for(int x = 0; x < length; x++)
    {
        std::cout<<data[x]<<" ";
    }
    std::cout<<std::endl;
}


int main(int argc, const char * argv[])
{
    // insert code here...
    //std::cout << "Hello, World!\n";

    int foo [] = { 18, 2, 77, 0, 12071 , 21, 45, 98, 54, 80};
    InsertSort(foo, 10);


    return 0;
}
#包括
void InsertSort(int数据[],int长度)
{

//std::cout
while(i>0…
应该是i>=0吗?
while(i>0…
应该是i>=0吗?你是对的。它现在可以工作了,但是伪代码现在被认为是错误的吗?伪代码在(i>0)时表示。我没有键入错误。@user1470901:伪代码正在使用从1索引的序列。啊,我明白了。非常感谢!你是对的。它现在可以工作了,但是伪代码现在被认为是错误的吗?伪代码在(I>0)时声明。我没有键入错误。@user1470901:伪代码使用从1索引的序列。啊,我明白了。非常感谢!