繁体   English   中英

冒泡排序优化C ++

[英]Bubble Sort Optimization C++

我只是在练习一点,并尝试使用冒泡排序算法对数组进行排序。 编译器没有给我任何警告或错误,它运作良好! 首先,您输入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循环。 我的意思是,它对数组进行排序,直到endarr_size的值相同。 但是通常不需要那么长时间。 我现在的问题......我怎样才能改进这个功能? 如何测试数组是否完全排序,以便while循环可以停止而不再运行另一个时间......

在您的for循环之前,假定已排序:

bool sorted = true;

在您的if语句中,记录未排序的内容:

sorted = false;

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

if ( sorted ) return;

在for循环的外面,放置一个布尔并将其设置为false。 在交换块内,将布尔值设置为true。 在for循环之后,检查boolean的值,如果仍然为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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM