在冒泡排序c++中,一旦元素都按正确顺序排序,我如何结束过程的显示
How can I end the display of passes as soon as the elements are all sorted in proper order in bubble sort c++?
这是我的全部代码:
void bubbleAsc(int arr[], int arraySize)
{
int i, j, temp, flag=1;
for(i=0; (i<arraySize-1) && flag; i++)
{
flag= 0;
for(j=0; j<(arraySize-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = 1;
}
}
cout<<"nnPass "<<i+1<<": ";
for(j=0; (j<arraySize); j++)
cout<<arr[j]<<" ";
cout<<endl;
}
}
main Bubble()
{
int i, arraySize, arr[50];
cout<<"Bubble Sort Algorithm"<<endl;
cout<<"nEnter the array size: ";
cin>>arraySize;
cout<<endl;
cout<<"Enter "<<arraySize <<" numbers: "<<endl;
for(i=0; i<arraySize; i++)
cin>>arr[i];
bubbleAsc(arr, arraySize);
cout<<"nnThe New Sorted Array in Ascending Order: n";
for(i=0; i<arraySize; i++)
cout<<arr[i]<<" ";
cout<<endl;
}
return 0;
}
以下是显示通行证的代码行:
cout<<"nnPass "<<i+1<<": ";
for(j=0; (j<arraySize); j++)
cout<<arr[j]<<" ";
cout<<endl;
我尝试输入5个数字,特别是{5,1,2,3,4},结果是:
排序前的数组:5 1 2 3 4
通过1:1 2 3 4 5
通过2:1 2 3 4 5
按升序排列的新排序数组:1 2 3 4 5
我想要的是,当元素已经按顺序排序时,过程的显示停止。在这种情况下,在Pass 1之后,应该不再有Pass 2,因为它与Pass 1相同。
数组一排序,代码就正确地停止排序。
但是打印输出完成了两次,因为您没有事先检查flag
:
cout<<"nnPass "<<i+1<<": ";
for(j=0; (j<arraySize); j++)
cout<<arr[j]<<" ";
cout<<endl;
您应该以if (flag)
为条件。
或者更好的是,在循环内部而不是外部使用标志:
for(int i=0; i<arraySize-1; i++)
{
bool stop = true;
for(int j=0; j<arraySize-i-1; j++)
{
if(arr[j]>arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
stop = false;
}
}
if (stop)
break;
cout<<"nnPass "<<i+1<<": ";
for(int j=0; j<arraySize; j++)
cout<<arr[j]<<" ";
cout<<endl;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 为什么在这个代码结束循环中没有得到结束
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 程序崩溃并显示"std::out_of_range"错误
- 试图对缓存进行跨步测试,但程序并没有结束
- Python中的for循环与C++有何不同
- 程序显示以退出代码 0; 结束
- 如何显示函数开始、结束行和函数体?
- 程序不会在必须时结束并显示输出
- WebSocket++服务器结束,但端口显示仍在使用中
- 在开关循环周期结束时未显示的游戏总量
- 应用程序在显示最终输出之前结束
- 在制作过程结束时显示警告/错误的数量
- 编译后的c++输出文件在程序结束时显示随机字符
- 在sentinel使用条件语句结束循环后显示最大值
- 我如何写一个Qt正则表达式来突出显示字符串开始和结束与非单词字符