簡體   English   中英

冒泡排序以無限循環結尾

[英]Bubble Sort ending in an infinite loop

我創建了一個氣泡排序程序。 它最終陷入無限循環。 我在地方添加了注釋,以便使代碼易於理解。 歡迎提供任何有關使代碼較小的建議。

我正在調試程序,發現了這一點-

當stdin為“ ccbbaa”,並且經過一些遞歸操作而最終輸入(aabbcc)和temp(aabbcc)相同時,則在執行strcmp()條件后,“ temp”的值將更改為“ baabcc”。

  1. 為什么會這樣呢? —這就是無限循環的原因。

  2. 字符數組的末尾是否有一個“ \\ 0”(將輸入復制到temp時)?

我通過使用for循環而不是strcmp()解決了這個問題。 研究為什么strcmp()當前不起作用。

提供了更新的代碼-http://ideone.com/4Bdblh (已解決)

越野車代碼

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>

void sort(char* input)
{
    const int length = strlen(input);
    int j = length -1;
    char temp[length];
    for(int i=0; i<length; i++)
    {
        temp[i]= *(input+i);
    }

    while(j)
    {
        if((int)*(input+1) < (int)*(input))
        {
            char temp1;
            temp1 = *(input);
            *input = *(input + 1);
            *(input + 1) = temp1;
        }
        input++;
        j--;
    }
        input = input - length +1;
        while(strcmp(temp,input))
        {
        sort(input);
        }
}
int main()
{
    char* input = malloc(sizeof(char)*1000);
    scanf("%[^\n]%*c",input);
    sort(input);
    printf("%s",input);
    return 0;
}

使用數組和循環的答案-

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
#define MAX 1000

void sort(char input[])
{
    const int length = strlen(input);
    int j = length -1;
    char temp[length];
    for(int i=0; i<length; i++)
    {
        temp[i]= input[i];
    }
    int l=0;
    while(j)
    {

        if(input[l+1] < input[l])
        {
            char temp1;
            temp1 = input[l];
            input[l] = input[l+1];
            input[l+1] = temp1;
        }
        l++;
        j--;
    }
        for(int k=0; k<length; k++)
        {
            if(temp[k]!=input[k])
            {
                sort(input);
            }
        }       
}
int main()
{
    char input[MAX];
    scanf("%[^\n]%*c",input);
    sort(input);
    printf("%s",input);
    return 0;
}

在C中,字符串只是一個以0結尾的char數組。

所有字符串函數均假定char數組以零結尾。

strcpy復制結尾處包含0分隔符的字符串。 因此,目的地必須有足夠的空間容納字符串加零。

strlen返回字符串的長度,因此目的地必須至少為strlen(輸入)+1長。

如果您以循環方式復制字符串,則不要忘記添加結尾的零。

我真正不明白的是為什么要使其遞歸並進行字符串比較以檢測完成情況。 您可以只實現兩個從0到長度-2的嵌套循環。保證將在最后進行排序。

如果要使其適應性強,只需存儲交換的最后位置即可。 您無需在下一個循環中走得更遠。

當stdin為“ ccbbaa”,並且經過一些遞歸操作而最終輸入(aabbcc)和temp(aabbcc)相同時,則在執行strcmp()條件后,“ temp”的值將更改為“ baabcc”。

  1. 為什么會這樣呢? —這就是無限循環的原因。

看起來'temp'的值已更改為“ baabcc”,因為該函數返回到先前的遞歸級別,其中本地temp以前的值相同。 無限循環的主要原因是由於while(strcmp(temp,input))一次又一次地比較了舊的,未排序的temp

  1. 字符數組的末尾是否有一個“ \\ 0”(將輸入復制到temp時)?

越野車代碼中的temp數組還沒有; 你本可以寫

    char temp[length+1];
    strcpy(temp, input);

或僅使用strncmp()而不是strcmp()

因此,要使程序正常工作,進行更改就足夠了

        while(strcmp(temp,input))

        if (strncmp(temp, input, length))

暫無
暫無

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

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