冒泡排序优化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循环。我的意思是它对数组进行排序,直到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;
}
相关文章:
- 空基优化子对象的地址
- 关闭||运算符优化
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 返回值优化:显式移动还是隐式
- 人脸跟踪arduino代码的优化
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 纯函数,为什么没有优化
- 为什么大多数 pair 实现默认不使用压缩(空基优化)?
- 如何以优化的方式同时迭代两个间距不相等的数组
- 小字符串优化(调试与发布模式)
- 浮点定向舍入和优化
- Visual Studio 调试优化如何工作?
- 为什么开关的优化方式与 c/c++ 中的链接不同?
- 线性优化目标函数中的绝对值
- GCC 会优化内联访问器吗?
- gcc 如何优化此循环?
- 如何防止 CUDA-GDB 中的<优化输出>值
- 为什么我的程序在 O0 和 O2 的优化级别返回不同的结果
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 使用 std::p air 进行返回值优化