Java Program For Sorting A Linked List That Is Sorted Alternating Ascending And Descending Orders
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 -> 40 -> 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 to merge sort on the 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 in descending order
- Merge both lists.
Below are the implementations of the above algorithm:
Given linked list 10 40 53 30 67 12 89 Sorted linked list 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.
Please refer complete article on Sort a linked list that is sorted alternating ascending and descending orders? for more details!
My Personal Notes arrow_drop_up
Please Login to comment...