By | 10.10.2016

# Merge Sort using Linked List

Write a C Program to implement Merge Sort using Linked List. Here’s simple C Program to implement Merge Sort using Linked List in C Programming Language.

A linked list cannot be accessed randomly and because of this slow access time, sorting algorithms like quick sort cannot be applied to it.

So we use merge sort for this purpose. It works on divide and conquer technique. Time complexity is O(nlogn).

Here is the source code of the C Program to implement Merge Sort using Linked List. The C program is successfully compiled and run(Codeblocks) on a Windows system. The program output is also shown below.

## SOURCE CODE : :

```/*  C Program to implement Merge Sort using Linked List  */

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

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

struct node *addnode(int number, struct node *next);
/* preform merge sort on the linked list */
/* merge the lists.. */

int main(void)
{
struct node *current;
struct node *next;
int n,i;

printf("Enter No. of elements u want to sort : ");
scanf("%d",&n);

int test[n];

printf("Enter elements : \n");
for(i=0;i<n;i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&test[i]);
}

/* insert some numbers into the linked list */
for(i = 0; i < n; i++)

/* sort the list */

/* print the list */
printf(" before  after\n"), i = 0;
for(current = head; current != NULL; current = current->next)
printf("%4d\t%4d\n", test[i++], current->number);

/* free the list */
for(current = head; current != NULL; current = next)
next = current->next, free(current);

/* done... */
return 0;
}

struct node *addnode(int number, struct node *next) {
struct node *tnode;

tnode = (struct node*)malloc(sizeof(*tnode));

if(tnode != NULL) {
tnode->number = number;
tnode->next = next;
}

return tnode;
}

/* preform merge sort on the linked list */
struct node *mergesort(struct node *head) {

}

}

/* merge the lists.. */

} else {
}

}```

### OUTPUT : :

```/*  C Program to implement Merge Sort using Linked List  */

Enter No. of elements u want to sort : 7

Enter elements :

Enter 1 element : 5
Enter 2 element : 2
Enter 3 element : 1
Enter 4 element : 4
Enter 5 element : 7
Enter 6 element : 9
Enter 7 element : 0

before  after
5       0
2       1
1       2
4       4
7       5
9       7
0       9```

Above is the source code for C Program to find area and circumference of circle which is successfully compiled and run on Windows System.The Output of the program is shown above .

If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.

5 1 vote
Article Rating
Category: C Programming Sorting Programs Tags: