Bubblesort игнорирует последний элемент - PullRequest
0 голосов
/ 07 июня 2018

Я пытаюсь отсортировать массив указателей, в зависимости от строк, на которые они указывают.Кажется, моя реализация пузырьковой сортировки игнорирует последний элемент, который я передаю.

#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 

Почему игнорируется последняя строка?Я что-то упускаю из виду?

Ответы [ 3 ]

0 голосов
/ 07 июня 2018

Вот что вызывает проблему:

short length = ptrpos-1;

//BEGIN BUBBLE SORT
for(short h = 1; h < length; h++)

Измените ваши циклы на

for(short h = 1; h <= length; h++)

Или измените for(ptrpos = 0;ptrpos <= length;ptrpos++) на
for(ptrpos = 0;ptrpos < length;ptrpos++) и, short length = ptrpos;

На данный момент цикл, используемый для сортировки, выполняется в один раз быстрее, чем требуется.Но цикл, который печатает, выполнил ожидаемое количество раз for(ptrpos = 0;ptrpos <= length;ptrpos++).

Еще несколько улучшений, которые я бы сделал:

  • Проверьте, вернул ли malloc NULL или нет, тогда только делайте дальнейший доступ.
0 голосов
/ 07 июня 2018

вот рабочая версия, я прокомментировал свои модификации

#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; //removed -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++) // transofrmed <= in <
        printf("%s",ptr[ptrpos]);

    return 0;
}
void swap(char **a,char **b) //swaps adresses of passed pointers
{
    char *temp = *a;
    *a = *b;
    *b = temp;
}
0 голосов
/ 07 июня 2018

Числа являются просто примерами.

ptrpos начинает отсчет с 0, что означает, что если у вас есть 6 элементов, ptrpos равно 6 после последней итерации вашегоwhile петля.Когда вы вычисляете длину с

short length = ptrpos-1;

, вы получаете length = 5.

Ваши for -циклы оканчиваются на counter < length, что означает, что они учитываются только до 4, что дает 5 элементов, а не 6.

Поскольку реальная длина массива равна 6, я предлагаю вам изменить упомянутую строку на

short length = ptrpos;

Теперь length будет равно количеству элементов в массиве.

...