Sorting singly linked list with bubble sort

91 Views Asked by At

I've written the following code for sorting a singly linked list using bubble sort. Sorting procedure should sort the nodes of the list on the basis of the data they contain. Sorting the nodes only exchanging the data among them won't be accepted. My code triggers a segmentation fault (core dumped). I think I'm not tracking the head pointer correctly. I'm sharing the full code for the reproduction of results.

#include<iostream>
using namespace std;   

typedef struct node
{
    int data;
    struct node *next;
} node;

node* create_node(node *head, int data)
{
    node *baby = (node*)malloc(sizeof(node));
    baby->data = data;
    baby->next = NULL;
    
    if(head==NULL)
        head = baby;
    else
    {
        node *curr = head;
        while(curr->next != NULL)
            curr = curr->next;
        curr->next = baby;  
    }
    return head;    
}

void sort_bubble(node *head)
{
    int count=0, i, j, temp;
    bool swapped;
    node *curr, *tempo, *p1, *p2;
    for(curr=head; curr!=NULL; curr=curr->next)
        count = count+1;
    
    for(i=0; i<=(count-2); i++)
    {
        curr = head;
        swapped = false;
        for(j=0; j<=(count-2-i); j++)
        {
            p1 = curr;
            p2 = p1->next;
            if(p1->data > p2->data)
            {
                tempo = p2->next;
                p2->next = p1;
                p1->next = tempo;
                curr = p2;
                swapped = true;
            }
            curr = curr->next;
        }
        if(swapped = false)
            break;
    }
}

void print_list(node *head)
{
    node *curr = head;
    while(curr)
    {
        cout<<curr->data<<" ";
        curr = curr->next;
    }
    cout<<"\n";
}

int main()
{
    int count = 6;
    node *head = NULL;
    
    head = create_node(head, 40);
    head = create_node(head, 10);
    head = create_node(head, 60);
    head = create_node(head, 50);
    head = create_node(head, 20);
    head = create_node(head, 30);
    print_list(head);
    
    sort_bubble(head);
    print_list(head);
    
    return 0;
}
1

There are 1 best solutions below

1
Luisa Sanchez On

Well, so far I can see this

if(swapped = false)

which makes the condition always false, and therefore the loop will never break. That makes the function run infinitely consuming CPU cycles which is probably what it throws the segmentation fault.