Kth smallest Element in unsorted Array

Source: Internet
Author: User

(Referrence:geeksforgeeks, Kth largest Element in Array)

This was a common algorithm problem appearing in interviews.

There is four basic solutions.

Solution 1--Sort first

A simple solution are to sort the given array using a O (n log n) sorting algorithm like Merge sort,heap sort, etc and retur n the element at index k-1 in the sorted array. Time complexity of this solution is O (n log n).

Java Arrays.sort ()

1  Public class solution{2      Public int findkthsmallest (intint  k) {3        arrays.sort (nums); 4         return Nums[k]; 5     }6 }
Solution 2--Construct Min Heap

A simple optomization are to create a Min Heap of the given n elements and call Extractmin () K times.

To build a heap, time complexity is O (n). So total time complexity is O (n + k log n).

Java Priority Queue

Using priorityqueue (collection<? extends e> c), we can construct a heap from array or other object in linear time.

By Defaule, it would create a min-heap.

Example

1  Public intGenerateheap (int[] nums) {2         intLength =nums.length;3integer[] NewArray =NewInteger[length];4          for(inti = 0; i < length; i++)5Newarray[i] =(Integer) nums[i];6Priorityqueue<integer> PQ =NewPriorityqueue<integer>(Arrays.aslist (NewArray));7}

Comparator Example

Comparator cmp = colletions.reverseorder ();

Solution 3--Use Max Heap

1. Build a max-heap of size K. Put Nums[0] to nums[k-1] to heap.

2. For each element after nums[k-1], the compare it with root of the heap.

A. If current >= root, move on.

B. If current < Root, remove root and put current into heap.

3. Return Root.

Time Complexity is O ((n-k) log k).

(Java:priorityqueue)

(codes)

1  Public classSolution {2      Public intFindkthsmallest (int[] Nums,intk) {3         //Construct A max heap of size K4         intLength =nums.length;5Priorityqueue<integer> PQ =NewPriorityqueue<integer>(k, Collections.reverseorder ());6          for(inti = 0; I < K; i++)7 Pq.add (Nums[i]);8          for(inti = k; i < length; i++) {9             intCurrent =Nums[i];Ten             intRoot =Pq.peek (); One             if(Current <root) { A                 //Remove Head - Pq.poll (); -                 //ADD new Node the Pq.add (current); -             } -         } -         returnPq.peek (); +     } -}
Solution 4--Quick Select
 Public classSolution {Private voidSwapint[] Nums,intIndex1,intindex2) {        intTMP =NUMS[INDEX1]; NUMS[INDEX1]=Nums[index2]; NUMS[INDEX2]=tmp; }    //Pick last element as pivot//Place all smaller elements before pivot//Place all bigger elements after pivot    Private intPartitionint[] Nums,intStartintend) {        intPivot =Nums[end]; intCurrentsmaller = start-1;  for(inti = start; I < end; i++) {            //If Current element <= Pivot, put it to right position            if(Nums[i] <=pivot) {Currentsmaller++;            Swap (Nums, I, Currentsmaller); }        }        //Put pivot to right positioncurrentsmaller++;        Swap (Nums, end, Currentsmaller); returnCurrentsmaller; }     Public intQuickselect (int[] Nums,intStartintEndintk) {intpos =partition (Nums, start, end)if(pos = = K-1)            returnNums[pos]; if(Pos < K-1)            returnQuickselect (Nums, pos + 1, end, K-(Pos-start + 1)); Else            returnQuickselect (Nums, start, pos-1, K); }}

The worst case time complexity of this method was O (N2), but it works with O (n) on average.

Kth smallest Element in unsorted Array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.