Given a Linked List. The Linked List is in alternating ascending and descending orders. Sort the list efficiently.
Input List: 10 -> 40 -> 53 -> 30 -> 67 -> 12 -> 89 -> NULL Output List: 10 -> 12 -> 30 -> 43 -> 53 -> 67 -> 89 -> NULL Input List: 1 -> 4 -> 3 -> 2 -> 5 -> NULL Output List: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Approach: The basic idea is to apply merge sort on linked list.
The implementation is discussed in this article: Merge Sort for linked List.
- Time Complexity: The merge sort of linked list takes O(n log n) time. In the merge sort tree the height is log n. Sorting each level will take O(n) time. So time complexity is O(n log n).
- Auxiliary Space: O(n log n), In the merge sort tree the height is log n. Storing each level will take O(n) space. So space complexity is O(n log n).
- Separate two lists.
- Reverse the one with descending order
- Merge both lists.
Below are the implementations of above algorithm.
Given Linked List is 10 40 53 30 67 12 89 Sorted Linked List is 10 12 30 40 53 67 89
- Time Complexity: O(n).
One traversal is needed to separate the list and reverse them. The merging of sorted lists takes O(n) time.
- Auxiliary Space: O(1).
No extra space is required.
Thanks to Gaurav Ahirwar for suggesting this method.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sort Matrix in alternating ascending and descending order rowwise
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- Sort first half in ascending and second half in descending order | 1
- Sort first half in ascending and second half in descending order | Set 2
- Sort first k values in ascending order and remaining n-k values in descending order
- Insertion sort to sort even and odd positioned elements in different orders
- Sorting rows of matrix in ascending order followed by columns in descending order
- Sorting rows of matrix in descending order followed by columns in ascending order
- PHP | Sort array of strings in natural and standard orders
- Given a linked list which is sorted, how will you insert in sorted way
- Merge K sorted Doubly Linked List in Sorted Order
- Sorting Vector of Pairs in C++ | Set 2 (Sort in descending order by first and second)
- Sort linked list which is already sorted on absolute values
- Sort a k sorted doubly linked list
- Python | Sort words of sentence in ascending order
- Sort an array of string of dates in ascending order
- Sort an array of Roman Numerals in ascending order
- Sort an Array of dates in ascending order using Custom Comparator
- Sort the given IP addresses in ascending order
- Program to sort string in descending order