2014-10-29 93 views
-1

在测试程序时我发现它给出了错误的输出。我一直在努力寻找错误,但我不能请帮助。需要冒泡排序反馈的错误输出

// 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

后我的建议是获取调试器并逐步完成代码。 – NPE 2014-10-29 09:49:06

+0

我已经试过,但我不能找到我的错误,因为我是编程新手 – johnnitro 2014-10-29 09:52:14

+1

然后你必须保持它。 Stackoverflow不是替代调试。 – dandan78 2014-10-29 09:58:08

回答

0

变化这条线为(INT I = 0;我< N; i ++在) 它将工作

+0

请接受适合您的解决方案或至少投票 – 2014-10-29 10:07:09

0

移动N--你的for循环

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); 
}