Why doesn't this bubble sort implementation of sorting linked lists work?
It doesn't sort at all.The main problem area of the code is int the sort function. I have verified that the main works well and the last pointer(next) of the linked list is set to null before calling the sort function. The chain that links the lists should be linked within the if statement that is within the string comparison block and it should return the first link on the list, which would be called by the while statement to access all the members that would have been sorted out, but , it doesn't seem to be working.
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NAME_SIZE 20
typedef struct record rec;
struct record
{
char name[NAME_SIZE];
int age;
rec* next;
};
void getname(char* name);
rec* sort(rec**First,int i);/*we need to change the addresses they refer to */
int main(void)
{
rec* Current = NULL;
rec* Previous = NULL;
rec* First = NULL;
char check = '\0';
int i = 0;
for(; ;)
{
fflush(stdin);
printf("\nDo you want to enter a%s record?(y/n): ", (check=='\0')?"":"nother");
scanf("%c", &check);
if(check == 'n')
break;
Current = (rec*)malloc(sizeof(rec));
if(First == NULL)
{
First = Current;
}
if(Previous != NULL)
{
Previous->next = Current;
}
printf("\n");
printf("\nPlease enter your name: ");
getname(Current->name);
printf("\nPlease enter your age: ");
scanf("%d", &Current->age);
Previous = Current;
Current->next = NULL;
i++;
}
Current = sort(&First, i);
while(Current != NULL)
{
printf("\n%s is %d years old ", Current->name, Current->age);
Current = Current->next;
}
return 0;
}
void getname(char *name)
{
fflush(stdin);
fgets(name, NAME_SIZE, stdin);
int length = strlen(name);
if(name[length - 1] == '\n')
name[length -1 ] = '\0';
return;
}
rec* sort(rec** first, int numbers)
{
rec* pTemp1 = NULL;
rec* pTemp2 = NULL;
rec* Temp_first = *first;
for(int j = 0; j < numbers; j++)
{
pTemp1 = *first;
if(((*first) = (*first)->next)==NULL)
{/*if end is reached, then break;*/
break;
}
if(strcmp((*first)->name, ((*first)->next->name)) > 0)
{
if(((*first)->next) != NULL)
{
printf("\n***XXX***Entered***XXX");
pTemp2 = (*first)->next;
(*first)->next = pTemp1;
pTemp1->next = pTemp2;
}
}
}
return Temp_first;
}
(Omitted freeing up memory for concise). Input
atest
aatest
btest
abtest
and the output isn't sorted:
atest
aatest
abtest