user3337714 user3337714 - 1 month ago 4x
C Question

C: Glitch?: Sort function NOT working on LINUX (RHEL 6.6), but MAC OS X (10.3)

I have a program to count the frequency of words from a text file. The node contains three key variables (

) and

  1. Add New word and set frequency to 1

  2. If existing word, increment frequency.

Sort Function is Bubble Sort

I created and ran the program in NetBeans & OS X terminal, and the program ran flawlessly without any problem. Giving me correct output.

Can someone please shed a light on what's wrong?

Compiling on Linux/Mac gcc -o file fileName.c

Entire Code

Sort Fucntion

void swap(struct Node *a, struct Node *b)
int temp = a->frequency;
a->frequency = b->frequency;
b->frequency = temp;

char tempS[50];
strcpy(tempS, a->word);

void sortList(struct Node *start)
int swapped;
struct Node *ptr1;
struct Node *lptr = NULL;

if (ptr1 == NULL)
swapped = 0;
ptr1 = start;

while (ptr1->next != lptr)
if (ptr1->frequency < ptr1->next->frequency)
swap(ptr1, ptr1->next);
swapped = 1;
ptr1 = ptr1->next;
lptr = ptr1;
while (swapped);


In each pass of the bubble sort, you need to check each node against the next, and swap if needed. Since you look at two nodes at a time, in ptr1 and ptr1->next, you need to end the loop when ptr1->next is NULL (no next node). To do that, you can change your loop condition from while (ptr1->next != lptr) to just while (ptr1->next), and eliminate lptr entirely.

In your code, you were comparing ptr1->next to lptr instead of NULL. Since lptr started off as NULL, your first pass was correct -- but at the end of each pass it was set to point at the last node instead, which meant that every loop pass after the first terminated one node early, and the last two nodes wouldn't be swapped even when they needed to be for a proper sort.