简体   繁体   English

使用 C++ 进行冒泡排序

[英]Bubble Sort using C++

I am attempting to bubble sort the values in the array "A" using c++, but get error saying stack around variable A is corrupted?我正在尝试使用 C++ 对数组“A”中的值进行冒泡排序,但收到错误消息,指出变量 A 周围的堆栈已损坏?

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int A[] = {5,7,8,2,4,3};

    for (int i = 1; i <= 7 - 1; i++)
    {
        for (int j = 7; j >= i + 1; j--)
        {
            if (A[j] < A[j - 1])
            {
                swap(A[j], A[j - 1]);
            }
        }
    }
}

I am attempting to ... sort the values in the array "A" ... using C++我正在尝试……对数组“A”中的值进行排序……使用 C++

Here, I'll sort them for you:下面我来给大家整理一下:

2, 3, 4, 5, 7, 8

(sigh) phew, that was some hard work! (叹气)呸,辛苦了! But at least now you don't need to bother with using C++.但至少现在您不需要为使用 C++ 而烦恼。



What, not good enough?什么,不够好? Oh, you really want to do it with C++ ?哦,你真的用 C++来做吗? Fine... here you go:好吧……给你:

#include <array>
#include <algorithm>

int main()
{
    auto A = make_array(5,7,8,2,4,3);
    std::sort(std::begin(A), std::end(A));
}

The make_array function is taken from here ; make_array函数取自此处 you also have std::experimental::make_array() , but that's not standardized yet.你也有std::experimental::make_array() ,但这还没有标准化。

Note this won't use bubble-sorting;请注意,这不会使用冒泡排序; but then - why would you want to bubble-sort?但是 - 你为什么要冒泡排序? It's quite inefficient as the array size increase... you might want to check out this comparison of sort algorithms (with neat animations too).随着数组大小的增加,它的效率非常低......您可能想查看排序算法的这种比较(也有简洁的动画)。

You don't need #include string since you are not using any string.您不需要 #include 字符串,因为您没有使用任何字符串。 Your initialization & conditions are wrong.您的初始化和条件错误。 Here is code that works:这是有效的代码:

My code:我的代码:

    #include <iostream>

    using namespace std;

    int main()
    {
       int A[] = {5, 7, 8, 2, 4, 3};
       int j = 1;
       int tmp;

       for(int i = 0; i < 6; i++){
          for(j = 0; j < 6-i-1; j++){
              if(A[j] > A[j + 1]){
                  tmp = A[j];
                  A[j] = A[j + 1];
                  A[j + 1] = tmp;
              }

          }
       }

       cout << "The sorted data in order: " << endl;
       for(int i = 0; i < 6; i++){
          cout << A[i] << endl;
       }


      return 0;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM