c - Bubblesort 忽略最后一个元素

标签 c sorting bubble-sort

我正在尝试根据指针指向的字符串对指针数组进行排序。我的 bubblesort 实现似乎忽略了我传递给它的最后一个元素。

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

void swap(char **a,char **b);
int main(void);

int main(void)
{
    char *ptr[1000]; //build an array of 1000 pointers
    short ptrpos = 0; //start at 0th pointer
    char input[500]; 
    printf("Enter strings(names), seperate by newline\nEOF(Ctrl-D) finishes the input process.\n");
    while(fgets(input,sizeof(input),stdin))
    {
        ptr[ptrpos] = malloc(strlen(input)+1); 
        strcpy(ptr[ptrpos],input); 
        ptrpos++; 
    }
    short length = ptrpos-1;

//BEGIN BUBBLE SORT
    for(short h = 1; h < length; h++)
    {
        for(short i = 0;i < length - h; i++)
        {
            if(strcmp(ptr[i],ptr[i+1]) > 0) 
                swap(&ptr[i],&ptr[i+1]); 
        }
    }
//END BUBBLE SORT
    printf("\n----- Sorted List -----\n");
    for(ptrpos = 0;ptrpos <= length;ptrpos++)
        printf("%s",ptr[ptrpos]);

    return 0;
}
void swap(char **a,char **b) //swaps adresses of passed pointers
{
    char *temp = *a;
    *a = *b;
    *b = temp;
}

输出看起来像这样:

Enter strings(names), seperate by newline
EOF(Ctrl-D) finishes the input process.
Echo
Charlie
Foxtrot
Alpha
Golf
Bravo
Delta

----- Sorted List -----
Alpha
Bravo
Charlie
Echo
Foxtrot
Golf
Delta 

为什么忽略最后一个字符串?我是否遗漏了一些明显的东西?

最佳答案

数字只是示例。

ptrpos0 开始计数这意味着如果你有 6 个元素,ptrpos6在你的 while 的最后一次迭代之后环形。当您使用

计算长度时
short length = ptrpos-1;

你得到 length = 5 .

你的 for -循环终止于 counter < length这意味着它们只计数到 4,这会产生 5 个元素而不是 6 个。

由于数组的实际长度是6,我建议你把提到的那行改成

short length = ptrpos;

现在length将等于数组中元素的数量。

关于c - Bubblesort 忽略最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50736629/

相关文章:

c++ - WINAPI CreateWindow 显示奇怪的结果

c# - 如何实现DataGridView的自动排序?

C++ 冒泡排序负数

c - 冒泡排序有问题

java - 调用方法时无限循环

c - 归并排序 C 实现

c - "Private"C 中带有 const 的结构成员

c - Lex:标识符与整数

C++ 多维排序

python - 在 Django 中计算用户排名的最佳方法是什么