冒泡排序优化c++

Bubble Sort Optimization C++

本文关键字:c++ 优化 冒泡排序      更新时间:2023-10-16

我只是练习了一点,并试图用冒泡排序算法对数组进行排序。编译器没有给我任何警告或错误,它工作得很好!首先输入10次数字,然后程序对它们进行排序并打印出来。

代码:

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

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

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

bool sorted = true;

在你的if语句'中,记录它没有排序:

sorted = false;

for循环'之后,如果没有证据表明它没有排序,则返回:

if ( sorted ) return;

在for循环之外放置一个bool值并将其设置为false。在交换块中,将bool设置为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;
}