我的插入排序对除第一个数字之外的每个数字进行排序。它从第二个元素到最后一个元素排序,但它从不包含第一个元素。插入排序有什么问题。我将这段代码基于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;
}
这是我的输出:18 0 2 21 45 54 77 80 98 12071
这是我从书中收到的伪代码
for j = 2 to A.length
key - A[j]
//Insert A[j] into the sorted sequence A[1.. j - 1]
i = j -1
while i > 0 and A[i] > key
A[i+1] = A[i]
i = i -1
A[i+1] = key
如果存在版权问题,我将删除伪代码。
正如您所看到的,我的第一个元素未排序,并且由于某种原因从未排序。我的代码出了什么问题?
答案 0 :(得分:4)
将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;
}