Search code examples
csortingbubble-sort

Bubblesort ignores last element


I am trying to sort an array of pointers, depending on the strings they are pointing to. My implementation of bubblesort seems to ignore the last element i pass on to it.

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

The output looks like this:

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 

Why is the last string ignored? Am I missing something obvious?


Solution

  • Numbers are just examples.

    ptrpos starts counting at 0 meaning that if you have 6 elements, ptrpos is 6 after the last iteration of your while loop. When you calculate length with

    short length = ptrpos-1;
    

    you get length = 5.

    Your for-loops terminate with counter < length meaning that they only count to 4 which yields 5 elements not 6.

    As the real length of the array is 6, I suggest you change the mentioned line to

    short length = ptrpos;
    

    Now length would be equal to the number of elements in the array.