簡體   English   中英

C++中的冒泡排序算法

[英]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;
}

我正在學習入門級計算機科學課程,目前正在嘗試編寫一個程序,該程序調用函數“bsort”以遞增順序排列數組“list”的元素,但我的輸出是 49 個零,而我不是確定為什么? 我的教授希望我們從 100 開始並以 51 結束(按降序)初始化數組“列表”。

您的初始化循環不正確。 像這樣嘗試

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

您的版本確實是list[100] = 100, list[99] = 99, etc但數組的大小只有 50。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM