2015-04-21 62 views
-3

我想在一个函数,而不是在线使用冒泡排序,而我似乎有它返回结果的问题。就像目前一样,它根本没有给我任何结果。这是我迄今编写的代码...C++冒泡排序(升序)函数没有返回结果

基本上,用户告诉程序他们要输入多少个数字(最多允许输入20个),然后按输入的顺序将它们输入到数组中。然后打印输入的值,排序并打印排序后的值。或者至少这是应该发生的事情。

感谢您的帮助!

#include <iostream> 

using namespace std; 

int vault[20] = {};   // array to store the 20 values 
int val = 0;    // variable to pass values to the array 
int amt = 0;    // variable to get the amount of numbers the user is going to enter 
int i = 0;     // loop counter 


// Bubble Sort Function Prototype 
void bubble (int (&vault)[20], int val); 

// Bubble Sort Function 
void bubble (int (&vault)[20], int val) 
{ 
int swap = 1;  // flag used to indicate swaps occuring 
int temp = 0;  // holder variable 
int x = 0;   // loop counter 
int y = 0;   // second loop counter 

for (x = 0; (x < val) && (swap = 1); x++) 
{ 
    swap = 0; 

    for (y = x+1; y < val; y++) 
    { 
     if (vault[x] > vault[y]) 
     { 
      temp = vault[x]; 
      vault[x] = vault[y]; 
      vault[y] = temp; 
      swap = 1; 
     } 
    } 
} 
return; 
} 



int main() 
{ 
cout << "Welcome to the Bubble Sort exe\n\n" << endl; 
cout << "Please enter in the amount of numbers you would like to enter: "; 
cin >> amt; 

cout << "Please enter the values you wish to enter: "; 
for(i = 0; i < amt; i++) 
{ 
    cin >> vault[i]; 
} 

cout << "The values you entered in order are: "; 
for (i = 0; i < amt; i++) 
{ 
    cout << vault[i] << ' '; 
} 

cout << "\n\nLet me just sort that for you!" << endl; 

bubble(vault, val); 

cout << "\n\nHere are the values in ascending order:\n" << endl; 
for (i = 0; i < val; i++) 
{ 
    cout << vault[i] << ' '; 
} 


system("pause"); 

return 0; 
} 
+0

Altough它不是一个真正的泡沫排序算法的问题是,你存储的大小所述阵列的在AMT进行排序和你VAL传递给排序函数,它以0初始化此外你检查是否I > amt; ... –

+0

这样做......当然,它的东西很小,让我在这上面绊倒。感谢您的帮助!此外,大家都口口声声说这是不是一个真正的冒泡排序,但我看到这个确切的形式遍布论坛,并从文件直接从我的教授,我想我失去了一些东西... – Dpry12

回答

1

马蒂亚斯指出我在正确的方向。我忘记初始化变量'val'。当我纠正这一点,它完美的作品。

至于大家说这是不是一个典型的泡沫排序,我看到的多个站点,并从我的教授幻灯片这个确切形式,什么是错的写它的这种方式?

我现在尝试此相反,而且它在我彻底失败(叹息):

void bubble (int (&vault)[20], int val) 
{ 
    bool swap = true;  // flag used to indicate swaps occuring 
    int temp = 0;   // holder variable 
    int x = 0;    // loop counter 
    int y = 0;    // second loop counter 

    while (swap = true) 
     { 
     swap = false; 
     x++; 
     for (y = 0; y < val - x; y++) 
     { 
      if (vault[y] > vault[y+1]) 
      { 
       temp = vault[y]; 
       vault[y] = vault[y+1]; 
       vault[y+1] = temp; 
       swap = true; 
      } 
     } 
    } 
} 
1

你写什么不是一个典型的泡沫排序算法。 Bubble-sort每次遍历整个数组,交换元素及其直接后继者,一遍又一遍地执行此操作,直到不再发生交换为止。

在传统的实现,有没有“嵌套的for循环。”有一个嵌套在while或repeat-until结构中的for循环。

该算法被称为“气泡”,是因为最低值“冒泡”顶端...与截留在非常粘的油的气泡的大致速度。

(有,比如说比较,壳牌排序,这是一个轻微的似乎的改动泡沫,使一个巨大的差异。而到了典型的和明确的快速排序。)