Problem Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. Order of elments in output lists doesn’t matter.
Example Input: List1: 10->15->4->20 lsit2: 8->4->2->10 Output: Intersection List: 4->10 Union List: 2->8->20->4->15->10 Solution Method 1 - Simple
Following are simple algorithms to get union and intersection lists respectively.
Intersection (list1, list2)
Initialize result list as NULL. Traverse list1 and look for its each element in list2, if the element is present in list2, then add the element to result.
[Read More]
Sort a linked list using merge sort
Merge sort looks like a best choice for sorting the linked list.At a first appearance, merge sort may be a good selection since the middle element is required to subdivide the given list into 2 halves, but we can easily solve this problem by moving the nodes alternatively to 2 lists.
We have discussed the sorting options for linked list here.
Merge sort is very special (in fact many standard sort libraries like in java internally uses a combination of merge sort and insertion sort) because it has the wonderful property of being a stable sort.
[Read More]
What's the fastest algorithm for sorting a linked list?
Merge sort is the best choice. At a first appearance, merge sort may be a good selection since the middle element is required to subdivide the given list into 2 halves, but we can easily solve this problem by moving the nodes alternatively to 2 lists.
It is reasonable to expect that you cannot do any better than O(N log N) in running time, whenever we use comparison based sorts.
[Read More]
Bottom-up Merge Sort
Recursive algorithm
In the earlier article I’ve described a recursive version of the Merge Sort Algorithm OR Top Down Merge sort. Of course every recursive algorithm can be written in an iterative manner .
Non recursive algorithm
So today I am going to present the bottom-up version of the same algorithm, written in a non-recursive fashion .
The main idea of the bottom-up merge sort is to sort the array in a sequence of passes .
[Read More]
Sorting
A sorting algorithm is an algorithm that sorts the data into some order, say from ascending to descending.
The sorting problem
Input: Array of numbers , unsorted. Eg.
Output : Same numbers sorted in some order, say increasing order. Eg.
Classification of sorting algorithms
Sorting algorithm can be classified in various ways.
Comparison sorts vs non comparison sorts
Various sorts