简体   繁体   English

冒泡排序C编程

[英]Bubble Sort C Programming

Hey folks ive come across another problem. 嘿,我遇到了另一个问题。 Im trying to do a bubble sort and a selection sort ive got my selection sort working. 我试图进行冒泡排序和选择排序ive使我的选择排序工作。 But im having trouble with my bubble sort.Here it is. 但是我在泡沫排序方面遇到了麻烦。

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

Any ideas why its not working. 任何想法为什么它不起作用。

You never enter the loop because of 您永远不会因为以下原因而进入循环

int nSwaps=0;

Also, you should consider using another algorithm for sorting. 另外,您应该考虑使用其他算法进行排序。 I would recommend qsort 我会推荐qsort

The problem is 问题是

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

so 所以

0==1 which is return 0(false) so you never enter the loop try to change it 0 == 1,即返回0(false),因此您永远不会进入循环尝试更改它

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

change nSwaps to 1 and it should work... 将nSwaps更改为1,它应该可以工作...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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