2013-03-20 176 views
2

我只是在练习一点点,并尝试使用冒泡排序算法对数组进行排序。编译器没有给我任何警告或错误,它运行良好!首先你输入一个数字10次,然后程序对它们进行排序并打印出来。泡沫排序优化C++

代码:

#include <iostream> 
using namespace std; 

void arr_sort(int* array, const int arr_size){ 

int temp = 0; //Temporary integer to store (if necessary) the current element 
int end = 0; //Run time condition 

while(end++ != arr_size){ // Will loop max. 10 times 

    for(int i = 0; i < arr_size; i++){ 

     if(array[i] > array[i + 1]){ //If the current element 
      temp = array[i]; //is bigger than the next 

      array[i] = array[i + 1];//Change the positions 
      array[i + 1] = temp;  
     } 
    } 
} 

} 

int main(){ 

int arr_input[10]; 

for(int i = 0; i < 10;i++)  //The user has to type 10 numbers 
    cin >> arr_input[i];  //which will be stored in this array 

arr_sort(arr_input, 10);  //sorts the array 

cout << endl << endl; 

for(int i = 0; i < 10; i++)  //Print out the array! 
    cout << arr_input[i] << ", "; 
cout << endl; 

return 0; 
} 

我唯一的问题是while循环在arr_sort功能。我的意思是它排序阵列,直到结束具有相同的值arr_size。但通常不需要那么长时间。我现在的问题...我如何改进这个功能?我如何测试数组是否完全排序,以便while循环可以停止而不需要运行另一个时间和另一个时间...?

+4

就在for循环之外,放置一个bool并将其设置为false。在交换块内,将布尔值设置为true。在for循环之后,检查布尔值的值,如果它仍然是false,则不会进行交换,因此数组已排序,因此请跳出while循环。 – jonhopkins 2013-03-20 15:05:45

+2

@ alex23考虑到提出的问题,你的评论是毫无意义的脱离主题。保存讨论论坛的随机想法,你会。或者,发布完整答案。 – mloskot 2013-03-20 15:08:33

回答

3

就在for循环之外,放置一个bool并将其设置为false。在交换块内,将布尔值设置为true。在for循环之后,检查布尔值的值,如果它仍然是false,则不会进行交换,因此数组已排序,因此请跳出while循环。

while(end++ != arr_size){ // Will loop max. 10 times 

    bool swapped = false; 
    for(int i = 0; i < arr_size; i++){ 

     if(array[i] > array[i + 1]){ //If the current element 
      temp = array[i]; //is bigger than the next 

      array[i] = array[i + 1];//Change the positions 
      array[i + 1] = temp; 
      swapped = true;  
     } 
    } 
    if (!swapped) break; 
} 
3

for循环之前,假设它的排序:

bool sorted = true; 

在你if statement`,记录中没有排序:

sorted = false; 

for loop`后,返回,如果没有证据表明它没有排序:

if (sorted) return; 
+0

我喜欢这个。我总是以布尔值开始为false,但实际上你的方法更直观一些 – jonhopkins 2013-03-20 15:10:31