【发布时间】:2021-05-11 02:56:09
【问题描述】:
int main() {
int arr[5];
for ( int i = 0; i < 5; i++) {
cin>>arr[i];
}
for (int i = 0; i < 5; i++) {
for ( int j = 1; j < 5; j++) {
if ( arr[j] < arr[j-1]) swap(arr[j], arr[j-1]);
}
}
for( int i = 0; i < 5; i++) cout<<" "<<arr[i]<<" "<<endl;
}
/* take an element then if the adjacent element is smaller, replace it with that and repeat this process */
我尝试删除 j 循环并将 j, j-1 替换为 i, i-1 但它会引发我无法弄清楚的错误,这是冒泡排序算法。我想了解那里的两个循环有什么用。
【问题讨论】:
-
这里需要2个循环,因为内部循环只保证索引范围
[0, 4 - i]中的最大元素移动到索引4-i。其余元素的顺序可能根本不会改变(只考虑最大元素在索引 0 处的情况) -
我建议您尝试在每个内部循环之后打印输出。您将意识到内部循环仅将元素按降序排列。
标签: c++ algorithm sorting data-structures bubble-sort