在测试程序时我发现它输出错误。我一直试图找到错误,但我不能请求帮助。
// bubble.cpp:定义控制台应用程序的入口点。 //
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
void bubbleSort3 ( int x [ ] , int n ) {
bool exchanges;
int temp;
do {
n--; //make loop smaller each time
exchanges = false; // assume this is last pass over array
for ( int i=0; i < n-1; i++ ) {
if (x [ i ] > x [ i+1 ]) {
temp = x[ i ];
x [ i ] = x [ i+1 ];
x [ i+1 ] = temp;
exchanges = true; // after exchange must look again
}
}
}
while (exchanges);
}
int _tmain(int argc, _TCHAR* argv[])
{
int array[4]={50,3,33,1};
bubbleSort3 ( array , 4 );
for (int i=0;i<4;i++){
cout << " "<< array[i]<< " ";
}
cout <<endl;
system("pause");
return 0;
}
答案 0 :(得分:0)
将此行更改为for(int i = 0; i&lt; n; i ++) 它会起作用
答案 1 :(得分:0)
在你的for循环之后移动n--
void bubbleSort3 ( int x [ ] , int n ) {
bool exchanges;
int temp;
do {
exchanges = false; // assume this is last pass over array
for ( int i=0; i < n-1; i++ ) {
if (x [ i ] > x [ i+1 ]) {
temp = x[ i ];
x [ i ] = x [ i+1 ];
x [ i+1 ] = temp;
exchanges = true; // after exchange must look again
}
}
n--; //make loop smaller each time
}
while (exchanges);
}