气泡排序逻辑错误

Bubble sort logical error?

本文关键字:错误 排序 气泡      更新时间:2023-10-16

我正在尝试做一个气泡排序,但我不知道代码中发生了什么。我是个菜鸟,很抱歉,如果我写的代码似乎很明显 ^。 ^

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