So this is the thing, I need to implement the bubble sort algorithm on linked lists. Yes, I saw many answers written in Stack Overflow that addresses this question. Almost all of them are implemented using pointers-to-pointers. Here, I tried to implement this using a referenced pointer rather than double pointers. I've spent more than a day to figure out what's wrong with my code.
My implementation of the bubble-sort and swap functions are as follows:
struct node
{
int data;
node* next;
node(int x)
{
data = x;
next = NULL;
}
};
node* swap(node *a, node *b){
node* temp = b->next;
b->next = a;
a->next = temp;
return b;
}
void bubbleSort(node*& head) {
node* ptr = head;
node* last = NULL;
int swapped;
do
{
swapped = 0;
ptr = head;
while (ptr->next != last)
{
if (ptr->data > ptr->next->data)
{
if (ptr == head)
{
head = swap(ptr, ptr->next);
swapped = 1;
}
else{
ptr = swap(ptr, ptr->next);
swapped = 1;
}
}
ptr = ptr->next;
}
} while (swapped);
}
The output for the above code (which is wrong) is as follows:
The original list =
2 -> 1 -> 4 -> 3 -> 6 -> 5 ->
The Sorted list =
1 -> 2 -> 4 -> 6 ->
I know this is some basics for most of you. But please I would be very grateful if you can take some of your time to see what's wrong with this code.
Isn't the fact that I've used referenced pointers fulfill the same things that will be done by double-pointers. For example, this bubble-sort implementation is done using double-pointers?
bubbleSort?nullptr?node* &, then I will have to use double-pointers right?