Can anyone help..why isn't this bubble sort working?
 ``1234567891011121314151617`` ``````void LList :: bubbleSort (LList A, int n) { Node *temp; temp = Head; int hold; for (int pass = 1; pass <= n-1; pass++) // number of passes needed for bubblesort is the number of elements-1 { for (int c = 0; c < n-pass; c++)//only runs for unsorted elements { if ((temp->data) > (temp->link->data))//if the score to the right is greater the below swaps it { hold = temp->data; temp->data = temp->link->data; temp->link->data = hold; } temp = temp->link;``````

It is passed the LList, and the number of items in the list...
`temp = Head;`
Maybe (Assuming my second is correctly deducted):
`temp = A.Head;`

Secondly: This function is within a list, and you are passing it a list (parameter A) you do not need to do that.

Thirdly: It would be better practice to swap the nodes, rather than the nodes' values.

Fourthly: You do not seem to be implementing the algorithm correctly. Try reading the following and checking to see if your program matches any pseudo-code implementation: http://en.wikipedia.org/wiki/Bubble_sort#Pseudocode_implementation
The algorithm should be fine, i'm taking it from previous projects... the comment should read if the score to the right is less...
Also, this function is part of my LList public functions...so head is equal to the caller's head...Still having an issue, can't seem to figure out why its not working.
Why are you passing an LList in as a parameter, when this already a method of LList? Is this intended to operate on a different instance of LList?
Let me clarify... I realized that and changed it..Looks like the below now..

 ``123456789101112131415161718192021`` ``````template void LList :: bubbleSort (int n) //bubbleSort for linked list { Node *temp; //temp Node pointer temp = Head; //start at the Head int hold; //hold variable for (int pass = 1; pass <= n-1; pass++) // number of passes needed for bubblesort is the number of elements-1 { for (int c = 0; c < n-pass; c++)//only runs for unsorted elements { if ((temp->data) > (temp->link->data) && (temp->link !=NULL))//if the score to the right (next) is greater the below swaps it { hold = temp->data; temp->data = temp->link->data; temp->link->data = hold; } temp = temp->link; } } }``````
If i comment out the line after the if statement that reads

`temp = temp->link`

It will successfully put the first two nodes in order...However, when that line is back in, the program crashes...
Topic archived. No new replies allowed.