在冒泡排序c++中,一旦元素都按正确顺序排序,我如何结束过程的显示

How can I end the display of passes as soon as the elements are all sorted in proper order in bubble sort c++?

本文关键字:何结束 显示 过程 排序 结束 c++ 冒泡排序 元素 顺序      更新时间:2024-09-30

这是我的全部代码:

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