簡體   English   中英

冒泡分揀程序,在DM編譯器中工作(在Windows上)而不在GCC上(Ubuntu)

[英]Bubble Sorting Program, Works in DM compiler(on windows) & not on GCC(Ubuntu)

我在C中制作了這個冒泡排序算法。它在DM中運行良好,但是在gcc中執行時,給出了錯誤的輸出。

#include <stdio.h>

int i,j;

void BubbleSort(int*a, int n) //to sort the numbers
{
    int temp;
    for(i=0; i<n;i++)
        for(j=n; j>i;j--)
            if (a[j]<a[j-1])
                {
                    temp=a[j];
                    a[j]=a[j-1];
                    a[j-1]=temp;
                }
}

void Display(int * a, int n) //to display
{
    printf("\nThe sorted numbers are:\n");
    for(i=0;i<n;i++)
        {
            printf("%d, ",a[i]);
        }
}

int main()
{
    int a[50],n,choice;
    printf("\nEnter no. of elements to sort: (max. 50) ");
    scanf("%d",&n);
    printf("\nEnter the numbers : ");

    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    BubbleSort(a,n);
    Display(a,n);

    return 0;

} //End of main

輸入:

5
2 1 5 3 4

DM輸出:

1, 2, 3, 4, 5,

GCC輸出:

1, 2, 3, 5, 4,

這是怎么發生的?

事實上,這種做法是可疑的。 你在這一行上超越原始數組:

if (a[j]<a[j-1])  // sketchy when j==n

您正在比較一個尚未初始化的值,因此a[n]處的值是初始化時的值。

這一行:

for(j=n; j>i;j--)

應該:

for(j=n-1; j>i;j--)

暫無
暫無

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

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