Reputation: 6023
I need to implement a function which can be find the kth minimum from doubly linked list.
I searched on internet and come to know about this :
My function testcase is looks like this :
for(int i = 0; i < 1000; ++i)
{
// create linked list with 1000 elements
int kthMinimum = findKthMin(LinkedList, i);
// validate kthMinimum answer.
}
Here linkedlist can be in anyorder, we have to assume randomized only.
Any idea or suggestion to find kth minimum from doubly linked list in efficient time?
Thanks
Upvotes: 0
Views: 1076
Reputation: 1387
If the list is doubly-linked, you can run the QuickSort algorithm on it. On my experience QuickSort is the fastest sorting algorithm (measured generating random lists, and pitting it against HeapSort and MergeSort). After that, simply walk the list k-positions to get your k-th smallest element.
QuickSort average time is O(n*log(n))
, walking the list will be O(k)
, which in its worst case is O(n)
. So, total time is O(n*log(n))
.
Upvotes: 0
Reputation: 6086
You can maintain a heap of size k
by doing the following:
k
first elements of the list.At the end of the algorithm, the k-th smallest element will be at the top of the heap.
Accumulate the first k elements + heapify the array: O(k)
Process the remaining part of the list O((n-k)ln(k)).
Upvotes: 2