# Sort List in C++

C++Server Side ProgrammingProgramming

Suppose we have a list, we have to sort this in O(n logn) time using constant space complexity, so if the list is like [4,2,1,3], then it will be [1,2,3,4]

To solve this, we will follow these steps −

• Define a method for merging two lists in sorted, order, that method is merge(), this takes two lists l1 and l2.

• The sort list method will work like below −

• while fast is not null and next of fast is also not null, do

• prev := slow

• slow := next of slow

• fast := next of next of fast

• next of prev := null

• l2 := sortList(slow)

• return merge(l1, l2)

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
while(fast && fast->next){
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = NULL;
ListNode* l2 = sortList(slow);
return mergeList(l1,l2);
}
ListNode* mergeList(ListNode* l1, ListNode* l2){
ListNode* temp = new ListNode(0);
ListNode* p =temp;
while(l1 && l2){
if(l1->val<=l2->val){
p->next = l1;
l1 = l1->next;
}else{
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
if(l1){
p->next = l1;
}
if(l2){
p->next = l2;
}
return temp->next;
}
};
main(){
vector<int> v = {4,2,1,3,5,19,18,6,7};
ListNode *h1 = make_list(v);
Solution ob;
print_list((ob.sortList(h1)));
}

## Input

[4,2,1,3,5,9,8,6,7]

## Output

[1, 2, 3, 4, 5, 6, 7, 18, 19, ]