冒泡排序 - 如何使用它?

Bubble Sorting - How to use it?

我对编程有点陌生,试图了解算法的概念,所以我从排序开始 Algorithms.So 我阅读了很多关于它的内容并试图理解它的想法,然后从冒泡排序开始,但我有我的代码有问题,有人能告诉我我是否正确考虑过这个问题吗?我不确定我是否仍然走在正确的道路上。

编辑:我想让用户在数组中插入一定数量的数字,然后使用冒泡排序交换这些未排列的数字。

所以这是代码:

#include <iostream>
using namespace std;

int main(){
    int arr[6];
    int temp;
    cout << "Enter an unarranged amount of numbers(6) \n";
    for(int i=0;i<6;i++){
        cin>>arr[i];
    }
    cout << "Normal List : ";
    for(int i=0;i<6;i++){
        cout << arr[i] << " ";
    }
      //Sorting
    for(int i=0;i<6;i++){
        for(int x=0;x=i+1;x++){
            if(arr[i]>arr[x]){
                temp=arr[x];
                arr[x]=arr[i];
                arr[i]=temp;
            }
        }
         cout << arr[i] << " ";
    }
    return 0;
}

这个循环

for(int x=0;x=i+1;x++){

是一个无限循环,因为在循环条件中使用了赋值

x=i+1

所以作为条件值的 x 的值永远不会等于 0。

冒泡排序算法比较和交换数组的相邻元素。

您也可以使用标准函数 std::swap 来交换数组的元素。

实现冒泡排序的循环可以按照下面的演示程序所示的方式进行查找

#include <iostream>
#include <utility>

int main() 
{
    const size_t N = 6;

    int arr[N];

    std::cout << "Enter an unarranged amount of " << N << " numbers: ";

    for ( auto &item : arr ) std::cin >> item;

    std::cout << "Before sorting: ";
    for ( const auto &item : arr ) std::cout << item << ' ';
    std::cout << '\n';

    for ( size_t n = N, last = n; !( n < 2 ); n = last )
    {
        for ( size_t i = last = 1; i < n; i++ )
        {
            if ( arr[i] < arr[i-1] )
            {
                std::swap( arr[i], arr[i-1] );
                last = i;
            }
        }
    }

    std::cout << "After  sorting: ";
    for ( const auto &item : arr ) std::cout << item << ' ';
    std::cout << '\n';

    return 0;
}

其输出可能类似于

Enter an unarranged amount of 6 numbers: 6 3 1 2 4 5
Before sorting: 6 3 1 2 4 5 
After  sorting: 1 2 3 4 5 6 

至于你的代码,那么内部循环应该至少看起来像

    for(int x = 1; x < 6; x++ ){
        if ( arr[x-1] > arr[x] ){
            temp=arr[x];
            arr[x]=arr[x-1];
            arr[x-1]=temp;
        }
    }

并在循环后删除此语句

cout << arr[i] << " ";