I know its sad, but I am having trouble getting a bubble sort to work. Its meant to sort text by iterating through the pointers in the list. Somethings wrong tho and it only seems to half-sort it. Heres the function:
Code:
void SortList(list *head)
{
list *here;
list *there;
char temp[SIZE];
while(head->next != NULL)
{
here=head;
while(1)
{
there=here->next;
if(there == NULL) break;
if(strcmp(here->data, there->data) >0)
{
strcpy(temp, here->data);
strcpy(here->data, there->data);
strcpy(there->data, temp);
}
here=there;
}
head=head->next;
}
}
And heres a full/compilable version:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
struct list
{
char data[SIZE];
struct list *next;
};
typedef struct list list;
list *NewNode(list **head);
void PrintList(list *p);
int CountList(list *p);
void SortList(list *here);
int main()
{
char temp[SIZE];
list *head=NULL;
while(1)
{
fgets(temp, SIZE, stdin);
if(temp[0]=='\n')break;
temp[strlen(temp)-1]='\0';
head=NewNode(&head);
strcpy(head->data, temp);
}
SortList(head);
//BSort(head);
PrintList(head);
printf("List Entries: %i", CountList(head));
getchar();
}
list *NewNode(list **head)
{
list *newnode;
//Allocate space for new item
if(!(newnode = malloc(sizeof(*newnode))))
return NULL;
newnode->next=*head; //Next pointer is the existing head
*head = newnode; //Make the new node the head
newnode->data[0]='\0';
return newnode;
}
void PrintList(list *p)
{
while(p != NULL)
{
printf("Data: %s\t-\tAt Memory Address: %i\n", p->data, p);
p=p->next;
}
}
int CountList(list *p)
{
int count=0;
while(p != NULL)
{
count++;
p=p->next;
}
return count;
}
void SortList(list *head)
{
list *here;
list *there;
char temp[SIZE];
while(head->next != NULL)
{
here=head;
while(1)
{
there=here->next;
if(there == NULL) break;
if(strcmp(here->data, there->data) >0)
{
strcpy(temp, here->data);
strcpy(here->data, there->data);
strcpy(there->data, temp);
}
here=there;
}
head=head->next;
}
}