气泡排序逻辑错误
Bubble sort logical error?
我正在尝试做一个气泡排序,但我不知道代码中发生了什么。我是个菜鸟,很抱歉,如果我写的代码似乎很明显 ^。 ^
main() {
int a[5], i, j, smallest, temp;
cout << "Enter 5 numbers: " << endl;
for ( i = 0; i <= 4; i++ ) {
cin >> a[i];
}
for ( i = 0; i <=4; i++ ) {
smallest = a[i];
for ( j = 1; j <= 4; j++ ) {
if ( smallest > a[j] ) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
cout << endl << endl;
for ( i = 0; i <= 4; i++ ) {
cout << a[i] << endl;
}
system("pause");
}
任何答案都将不胜感激。谢谢!
您的Bubblesort几乎似乎是一种选择。Bubblesort查看成对的物品,并在必要时交换它们。选择排序查找其余数组中最低的项目,然后交换。
#include <iostream>
#include <utility>
using std::cin;
using std::cout;
using std::endl;
using std::swap;
void bubblesort(int a[5])
{
bool swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < 4; i++)
{
if (a[i] > a[i + 1])
{
swap(a[i], a[i + 1]);
swapped = true;
}
}
}
}
void selectionSort(int a[5])
{
for (int i = 0; i < 4; i++)
{
int smallest = i;
for (int j = smallest; j < 5; j++)
{
if (a[smallest] > a[j])
{
smallest = j;
}
}
if (smallest != i)
{
swap(a[i], a[smallest]);
}
}
}
int main(int argc, char* argv[])
{
int a[5];
cout << "Enter 5 numbers: " << endl;
for (int i = 0; i < 5; i++ )
{
cin >> a[i];
}
//selectionSort(a);
bubblesort(a);
cout << endl << endl;
for (int i = 0; i <= 4; i++ ) {
cout << a[i] << endl;
}
}
相关文章:
- C++选择排序算法中的逻辑错误
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 显示错误输出的简单数组排序程序
- 对单向链表进行排序时出现运行时错误
- 无法在我的堆排序代码中找到错误.无法正确执行.C++
- 在气泡排序程序中未声明错误功能
- 仅在大型阵列上出现合并排序分段错误
- 分段 排序函数实现中的错误
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 字符串上的合并排序上的 Seg 错误
- 将图形表示为unordered_map<字符串、向量>时拓扑排序错误<string>
- C++为什么我的指针选择排序中存在分段错误?
- 我想在 c++ 中对单向链表进行冒泡排序,但我一直面临左值错误,无法解决它
- 尝试按值对地图进行排序,但出现错误
- 使用快速排序对 C++ 中的可视化工具错误进行排序
- 合并排序:分段错误核心转储
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- 合并排序中的错误计数:计数反转
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- C++中的错误排序算法