冒泡排序优化 C++

Nor*_* Me 2 c++ bubble-sort

我只是练习了一点,并尝试使用冒泡排序算法对数组进行排序。编译器没有给我任何警告或错误,它运行良好!首先,您输入 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;
}
Run Code Online (Sandbox Code Playgroud)

我唯一的问题是 arr_sort 函数中的 while 循环。我的意思是它对数组进行排序,直到endarr_size具有相同的值。但通常不需要那么长时间。我现在的问题......我怎样才能改进这个功能?如何测试数组是否完全排序,以便while循环可以停止而无需再次运行......?

Dre*_*ann 6

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

bool sorted = true;
Run Code Online (Sandbox Code Playgroud)

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

sorted = false;
Run Code Online (Sandbox Code Playgroud)

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

if ( sorted ) return;
Run Code Online (Sandbox Code Playgroud)