Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C Exercises: Sort a given linked list by bubble sort

C Linked List : Exercise-30 with Solution

Write a C programming to sort a given linked list by bubble sort.

Sample Solution:

C Code:

// Licence: https://bit.ly/2JK1psc
#include<stdio.h>
#include <stdlib.h>
struct node
{
  int data;
  struct node *next;
};
int main()
{
	struct node *temp1,*temp2, *t,*newNode, *startList;
	int n,k,i,j;
	startList=NULL;
	printf("Input number of elements in the linked list?");
	scanf("%d",&n);
	printf("Input the elements in the linked list:\n");
	for(i=1;i<=n;i++)
	{
    		if(startList==NULL)
    		{
			newNode=(struct node *)malloc(sizeof(struct node));
			scanf("%d",&newNode->data);
			newNode->next=NULL;
			startList = newNode;
			temp1=startList;
		}
		else
		{
			newNode=(struct node *)malloc(sizeof(struct node));
			scanf("%d",&newNode->data);
			newNode->next=NULL;
			temp1->next = newNode;
			temp1=newNode;
		}
	}
	for(i=n-2;i>=0;i--)
	{
		temp1=startList;
		temp2=temp1->next;
		for(j=0;j<=i;j++)
		{
			if(temp1->data > temp2->data)
			{
				k=temp1->data;
				temp1->data=temp2->data;
				temp2->data=k;
			}
			temp1=temp2;
			temp2=temp2->next;
		}
	}
	printf("Sorted order is: \n");
	t=startList;
	while(t!=NULL)
	{
		printf("%d\t",t->data);
		t=t->next;
	}
}

Sample Output:

 Input number of elements in the linked list? 5
 Input the elements in the linked list: 15
33
49
6
65

Sorted order is: 
6	15	33	49	65

Flowchart :

Flowchart: Sort a given linked list by bubble sort.

C Programming Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a program in C to search an element in a circular linked list.
Next: C Programming Exercises on Numbers Home

What is the difficulty level of this exercise?



C Programming: Tips of the Day

Static variable inside of a function in C

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

Ref : https://bit.ly/3fOq7XP