use*_*901 0 c++ arrays sorting
我的插入排序对每个数字进行排序,但第一个数字除外。它从第二个元素到最后一个元素排序,但它从不包括第一个元素。我的插入排序有什么问题。我根据 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;
}
Run Code Online (Sandbox Code Playgroud)
这是我的输出: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
Run Code Online (Sandbox Code Playgroud)
如果有版权问题,我会把伪代码拿下来。
如您所见,我的第一个元素未排序,并且由于某种原因从未排序。我的代码有什么问题?
将while循环更改为
while(i >= 0 && data[i] > key)
Run Code Online (Sandbox Code Playgroud)
这是更新后的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)