# Sort a Linked list using C

### Tags:

#### data-structures

I am trying to sort a Linked list, but not able to do it. Below is my code. Can anyone help me. I have seen some programs too, which sort linked list and their approach is also like this only.

``````#include <stdio.h>
#include <stdlib.h>

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

int push(struct node **h, int x)
{
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->data = x;
temp->next = *h;
*h = temp;
return 0;
}

void print(struct node *head)
{
struct node *temp = head;
while(temp != NULL)
{
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}

void sort(struct node **h)
{
int i,j,a;

struct node *temp1;
struct node *temp2;

for(temp1=*h;temp1!=NULL;temp1=temp1->next)
{
for(temp2=temp1->next;temp2!=NULL;temp2=temp2->next)
{
a = temp1->data;
temp1->data = temp2->data;
temp2->data = a;
}
}
}

int main()
{
struct node * head = NULL;
printf("List is : ");
printf("after sorting list is : ");
return 0;
}
``````

Below is the output which i am getting :

``````List is : 9 2 6 4 5
after sorting list is : 5 4 6 2 9
``````
732
asked Mar 11 '23 15:03

#### Vivek

You're switching the elements no matter what. Compare them first and then swap them if temp2 is less than temp1:

``````void sort(struct node **h)
{
int i,j,a;

struct node *temp1;
struct node *temp2;

for(temp1=*h;temp1!=NULL;temp1=temp1->next)
{
for(temp2=temp1->next;temp2!=NULL;temp2=temp2->next)
{
if(temp2->data < temp1->data)
{
a = temp1->data;
temp1->data = temp2->data;
temp2->data = a;
}
}
}
}
``````
161
answered Mar 20 '23 19:03

## Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!