我遵循计算算法并在C ++中实现它,但输出不符合要求。 它应输出35 60 81 98。
计算算法
1. for i=0 to n-1 do
2. count[i] = 0
3. end for
4. for i =0 to n-2 do
5. for j = i+1 to n-1 do
6. if A[i] < A[j]
7. count[j] = count[j] +1
8. else count[i] = count[i] +1
9. end if
10. end for
11. end for
12. for I = 0 to n-1
13. S[count[i]] = A[i]
14. End for
15. Return S
已实施代码
int main(){
int A[4] = {60, 35, 81, 98};
int count[4], S[5];
int i, n=4, j;
system("cls");
for(i=0; i<n-1; i++){
count[i] = 0;
}
for(i=0; i<n-2; i++){
for(j=i+1; j<n-1; j++){
if(A[i] < A[j]){
count[j] = count[j] + 1;
}else{
count[i] = count[i] + 1;
}
}
}
for(i=0; i<n-1; i++){
S[count[i]] = A[i];
}
for(i=0; i<n; i++){
cout << S[i] << endl;
}
getchar();
}
输出
35
60
81
1976672506
我哪里出错了?最后一个数字不正确。请帮忙!
答案 0 :(得分:0)
for(i=0; i<n-1; i++){
for(j=i+1; j<n; j++){
if(A[i] < A[j]){
count[j] = count[j] + 1;
}else{
count[i] = count[i] + 1;
}
}
}
这是你应该使用的!
请注意,我再次运行两个循环(也考虑数组的最后一个元素,否则会丢失!)
此外,在填充已排序的数组时:
for(i=0; i<n; i++){
S[count[i]] = A[i];
}
答案 1 :(得分:0)
你有错误的部分。然后我在下面编辑了你的代码和编辑版本:
for (i = 0; i<n; i++){
count[i] = 0;
}
//if i<n in bellow for no problem occure
for (i = 0; i<n -1; i++){
for (j = i + 1; j<n; j++){
if (A[i] < A[j]){
count[j] = count[j] + 1;
}
else{
count[i] = count[i] + 1;
}
}
}
for (i = 0; i<n ; i++){
S[count[i]] = A[i];
}
for (i = 0; i<n; i++){
cout << S[i] << endl;
}