简体   繁体   中英

Bubble Sort Algorithm in c++

#include <iostream>

using namespace std;

int list [50];
void bsort(int list[], int n);
void printArray(int list[], int n);

int main ()
{
    for (int i = 100; i > 50; i--)
    {
        list[i] = i;
        cout << list[i] << endl;
    }
    int n = sizeof(list) / sizeof(list[0]);
    bsort(list, n);
    printArray(list, n);

  return 0;
}

void bsort(int list[], int n)
{
   int i, j;
        for (i = 0; i <= 48; i++)
        {
            for (j = i+1; j <= 49; j++)
            {
                int temp;
                if (list[i] > list[j])
                {
                    temp = list[i];
                    list[i] = list [j];
                    list[j] = temp;
                }
            }
        }
}
void printArray(int list[], int n)
{
    for (int i = 0; i < n; i++)
        cout << list[i] << " ";
    cout << endl;
}

I'm in an intro-level computer science course and I am currently trying to write a program that calls the function 'bsort' to arrange the elements of the array 'list' in increasing order but my output is 49 zeros and I am not sure why? My professor wanted us to initialize the array 'list' starting at 100 and ending with 51 (in decreasing order).

Your initialisation loop is incorrect. Try like this

for (int i = 0; i < 50; i++)
{
    list[i] = 100 - i;
    cout << list[i] << endl;
}

Your version did list[100] = 100, list[99] = 99, etc but the array only has size 50.

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