{"id":27708,"date":"2018-04-09T20:22:57","date_gmt":"2018-04-09T14:52:57","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27708"},"modified":"2018-09-11T19:21:05","modified_gmt":"2018-09-11T13:51:05","slug":"k-largestor-smallest-elements-array-added-min-heap-method","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/k-largestor-smallest-elements-array-added-min-heap-method\/","title":{"rendered":"k largest(or smallest) elements in an array | added Min Heap method"},"content":{"rendered":"<p><strong>Question: <\/strong>Write an efficient program for printing k largest elements in an array. Elements in array can be in any order.<span id=\"more-2392\"><\/span><\/p>\n<p>For example, if given array is [1, 23, 12, 9, 30, 2, 50] and you are asked for the largest 3 elements i.e., k = 3 then your program should print 50, 30 and 23.<\/p>\n<div id=\"practice\">\n<h2 id=\"recommended-please-solve-it-on-practice-first-before-moving-on-to-the-solution\"><a href=\"http:\/\/practice.geeksforgeeks.org\/problems\/k-largest-elements\/0\" target=\"_blank\" rel=\"noopener\">Recommended: Please solve it on &#8220;<b><i><u>PRACTICE<\/u><\/i><\/b>&#8221; first, before moving on to the solution.<\/a><\/h2>\n<p><strong><br \/>\nMethod 1 (Use Bubble k times)<\/strong><br \/>\nThanks to Shailendra for suggesting this approach.<br \/>\n1) Modify <a href=\"http:\/\/en.wikipedia.org\/wiki\/Bubble_sort\" target=\"_blank\" rel=\"noopener\">Bubble Sort<\/a> to run the outer loop at most k times.<br \/>\n2) Print the last k elements of the array obtained in step 1.<\/p>\n<p>Time Complexity: O(nk)<\/p>\n<p>Like Bubble sort, other sorting algorithms like <a href=\"http:\/\/en.wikipedia.org\/wiki\/Selection_sort\" target=\"_blank\" rel=\"noopener\">Selection Sort<\/a> can also be modified to get the k largest elements.<\/p>\n<p><strong>Method 2 (Use temporary array)<\/strong><br \/>\nK largest elements from arr[0..n-1]\n<p>1) Store the first k elements in a temporary array temp[0..k-1].<br \/>\n2) Find the smallest element in temp[], let the smallest element be <em>min<\/em>.<br \/>\n3) For each element <em>x<\/em> in arr[k] to arr[n-1]\nIf <em>x <\/em>is greater than the min then remove <em>min <\/em>from temp[] and insert <em>x<\/em>.<br \/>\n4) Print final k elements of <em>temp[]<\/em><\/p>\n<p>Time Complexity: O((n-k)*k). If we want the output sorted then O((n-k)*k + klogk)<\/p>\n<p>Thanks to nesamani1822 for suggesting this method.<\/p>\n<p><strong>Method 3(Use Sorting)<\/strong><br \/>\n1) Sort the elements in descending order in O(nLogn)<br \/>\n2) Print the first k numbers of the sorted array O(k).<\/p>\n<p>Time complexity: O(nlogn)<\/p>\n<p><strong>Method 4 (Use Max Heap)<\/strong><br \/>\n1) Build a Max Heap tree in O(n)<br \/>\n2) Use <a href=\"http:\/\/www.cs.utsa.edu\/~dj\/cs3343\/lecture7.html\" target=\"_blank\" rel=\"noopener\">Extract Max<\/a> k times to get k maximum elements from the Max Heap O(klogn)<\/p>\n<p>Time complexity: O(n + klogn)<\/p>\n<p><strong>Method 5(Use Oder Statistics)<\/strong><br \/>\n1) Use order statistic algorithm to find the kth largest element. Please <a href=\"http:\/\/www.cse.ust.hk\/~dekai\/271\/notes\/L05\/L05.pdf\" target=\"_blank\" rel=\"noopener\">see the topic selection in worst-case linear time <\/a>O(n)<br \/>\n2) Use <a href=\"http:\/\/en.wikipedia.org\/wiki\/Quicksort\" target=\"_blank\" rel=\"noopener\">QuickSort <\/a>Partition algorithm to partition around the kth largest number O(n).<br \/>\n3) Sort the k-1 elements (elements greater than the kth largest element) O(kLogk). This step is needed only if sorted output is required.<\/p>\n<p>Time complexity: O(n) if we don\u2019t need the sorted output, otherwise O(n+kLogk)<\/p>\n<p>Thanks to <a href=\"http:\/\/www.geeksforgeeks.org\/forum\/topic\/print-k-largest-numbers\" target=\"_blank\" rel=\"noopener\">Shilpi <\/a>for suggesting the first two approaches.<\/p>\n<p><strong>Method 6 (Use Min Heap)<\/strong><br \/>\nThis method is mainly an optimization of method 1. Instead of using temp[] array, use Min Heap.<\/p>\n<p>Thanks to <a href=\"http:\/\/www.geeksforgeeks.org\/forum\/topic\/kth-largest-element\" target=\"_blank\" rel=\"noopener\">geek4u <\/a>for suggesting this method.<\/p>\n<p>1) Build a Min Heap MH of the first k elements (arr[0] to arr[k-1]) of the given array. O(k)<\/p>\n<p>2) For each element, after the kth element (arr[k] to arr[n-1]), compare it with root of MH.<br \/>\n\u2026\u2026a) If the element is greater than the root then make it root and call <a href=\"http:\/\/www.personal.kent.edu\/~rmuhamma\/Algorithms\/MyAlgorithms\/Sorting\/heapSort.htm\" target=\"_blank\" rel=\"noopener\">heapify <\/a>for MH<br \/>\n\u2026\u2026b) Else ignore it.<br \/>\n\/\/ The step 2 is O((n-k)*logk)<\/p>\n<p>3) Finally, MH has k largest elements and root of the MH is the kth largest element.<\/p>\n<p>Time Complexity: O(k + (n-k)Logk) without sorted output. If sorted output is needed then O(k + (n-k)Logk + kLogk)<\/p>\n<p>All of the above methods can also be used to find the kth largest (or smallest) element.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Question: Write an efficient program for printing k largest elements in an array. Elements in array can be in any order. For example, if given array is [1, 23, 12, 9, 30, 2, 50] and you are asked for the largest 3 elements i.e., k = 3 then your program should print 50, 30 and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":31258,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73012,80127],"tags":[81996,82000,72887,81997,81998,82001,82002,81999],"class_list":["post-27708","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures","category-heap","tag-find-k-largest-elements-in-array","tag-find-kth-largest-element-in-max-heap","tag-find-kth-smallest-element-in-array-java","tag-kth-largest-element-in-an-array-geeksforgeeks","tag-kth-largest-element-in-an-array-leetcode","tag-kth-largest-element-in-array-in-c","tag-kth-smallest-element-in-an-array-in-c","tag-kth-smallest-element-in-an-array-without-sorting"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27708","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27708"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27708\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31258"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27708"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27708"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27708"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}