简体   繁体   中英

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?

#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++

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++.



What, not good enough? Oh, you really want to do it with 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 ; you also have std::experimental::make_array() , but that's not standardized yet.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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