簡體   English   中英

冒泡排序C編程

[英]Bubble Sort C Programming

嘿,我遇到了另一個問題。 我試圖進行冒泡排序和選擇排序ive使我的選擇排序工作。 但是我在泡沫排序方面遇到了麻煩。

void sortBubble(int nRow, char sArr[5][10], char sArrTemp[10]) {
    int nSwaps=0;
    while(nSwaps==1) {
        nSwaps=0;
        for(nRow=1;nRow <5;nRow++) {
            if(strcmp(sArr[nRow-1],sArr[nRow])<0) {
                puts("Doing Swap");
                strcpy(sArrTemp,sArr[nRow]);
                strcpy(sArr[nRow],sArr[nRow-1]);
                strcpy(sArr[nRow-1],sArrTemp);
                nSwaps=1;
            }
        }
    }
}

任何想法為什么它不起作用。

您永遠不會因為以下原因而進入循環

int nSwaps=0;

另外,您應該考慮使用其他算法進行排序。 我會推薦qsort

問題是

int nSwaps= 0 ; while(nSwaps== 1 )

所以

0 == 1,即返回0(false),因此您永遠不會進入循環嘗試更改它

    int nSwaps=0;
    while(nSwaps==1) {
     // sort
    }

將nSwaps更改為1,它應該可以工作...

int nSwaps=1;
while(nSwaps==1) {
 // sort
}

暫無
暫無

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

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