我正在通过Cormen的“算法导论”一书工作,并且我从伪代码创建了以下内容。但是,数组的前两个元素似乎没有进行排序。我无法发现错误(可能是因为它晚了)。所以我想知道是否有人能从第一眼看到。插入从T Cormen书中排序
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int input;
cout << "Enter length of desired array." << "\n";
cin >> input;
cout << "\n";
int A [input];
//Populate and print the Array.
for(int i=0; i<input; i++){
A[i] = rand()%99-1;
cout << A[i] << " ";
}
cout << "\n";
//Insertion sort.
for(int j=2; j<input; j++){ //Iterate through the Array.
int key = A[j]; //Store the current element into key.
int i = j-1; //Iterator for while loop.
while(i>0 && A[i]>key){ //Loop to insert A[j] into the sorted sequence.
A[i+1] = A[i]; //Move the element.
i=i-1; //New value of i.
A[i+1] = key; //Update the key
}
}
for(int i=0; i<input; i++){
cout << A[i] << " ";
}
return 0;
}
你试过调试过吗?你在最小数据集上运行吗? –
这本书使用1基础索引iirc,这将是你的问题。 – jli