Sort, ask for a few of the most value problems, enter n integers, and output the smallest of the k elements.

Source: Internet
Author: User

After reading the two algorithms to find the maximum value of some thoughts.

If you want to see directly the algorithm can be skipped. But I think these ideas are more useful, at least for my future algorithm design.

The more powerful the algorithm is, the slower it must be, because, according to the jungle rules, the slow and less functional algorithm will be eliminated.

So, (watch out!!) ), if we use an algorithm to feel the result of it to meet our use, and beyond, we use, then we are likely to waste time, reduce efficiency.

For example, the algorithm for the maximum of 10 in this 1000 number:

    1. If sorted, take the first 10. Found in the back of the white sort, no use to. There may be a quicker way to refer to bold lines.
    2. So we thought of the heap. The heap is built faster than sorting, because it is not lined up, but more teams, this is more scattered. It can also be said that the greater the entropy, will certainly be good to achieve. But we have found that we still have more conditions, that is, we take out an ordered sequence, actually does not use, the order of the 10 numbers we do not.
    3. So there is (4) given, find the 10th-largest element such an algorithm. Because nothing is wasted, so there is no faster. That's for sure.
    4. Finally, it is important to say that the fastest is often not the general method, to achieve their own.
Title Description: Enter n integers to output the smallest of the k elements.

For example: Enter the 8 digits of 1,2,3,4,5,6,7,8, then the smallest 4 digits are 1,2,3,4.

idea 1: The easiest way to think about this sequence is to start from small to large, then output the smallest number of k in front. If you choose quick sort to sort, the time complexity: O (N*LOGN)

Train of thought 2: on the basis of thinking 1 further think, the topic does not require to find the number of K, even after the number of n-k is orderly, so, why do we have all the n number of the row sequence? So, one of the ways that we can play is to: Traverse N number, First the first traversal to the K number into the size of the array of K, the number of K, the use of choice or exchange sorting, find the maximum number of K Kmax (Kmax set to K elements of the largest element in the array), Time O (k) (you should know, insert or select the sort to find operations need O (k)), After continuing the traversal after the number of n-k, X and Kmax comparison: If X<kmax, then x instead of Kmax, and re-find the K elements in the array of the largest element Kmax '; if X>kmax, the array is not updated. In this way, the time to update or not update the array is O (k) or O (0), and the total time complexity is averaged down to: N*o (k) =o (N*k)

Train of thought 3: similar to the idea 2 method, just use the largest heap of capacity K to replace the idea of the array in 2 (the maximum number from the array requires O (k) lookup, and from the update of a heap to make it the largest heap only need O (LOGK) operations). This is done as follows: The maximum number of k to be traversed with the largest heap of capacity K, and assuming that they are the smallest number of k, after the heap time O (k), there is K1<k2<...<kmax (Kmax is set to the largest element in the large top heap). Continue traversing the sequence, traversing an element x each time, comparing to the top element of the heap, X<kmax, updating the heap (spents logk), or not updating the heap. So down, the total time-consuming O (k + (n-k) *logk) =o (N*LOGK).

Idea 4: According to the description given in the beauty of programming, similar to the division method of fast sorting, N number is stored in the array s, and then randomly select a number from the array x (randomly selected pivot element, can achieve linear expected time O (N) complexity), the array is divided into Sa and SB part,sa< =X<=SB, if the K element to be found is less than the number of elements of the SA, the smaller k elements in the SA are returned, otherwise all elements in the SA +SB small k-| Sa| an element. Like the process described above, this fast-selecting select algorithm, which uses a fast-sorting partition, looks for the smallest element of k and, in the worst case, the complexity of O (N). Oh, it's cool, there's no!

idea 5: still use the data structure: heap. The method is as follows: to build the minimum heap for the whole array sequence, the time to build the heap is O (n), then the number of the first k in the heap is taken, the total time complexity is: O (n+k*logn).

idea 6: similar to the above idea 5, the difference is that the element array in situ to build the smallest heap O (n), and then extract the K, but each time the extraction, the top of the element to move to a maximum of k times is sufficient , the number of down-shift successive reduction ( And the above ideas 5 each extraction need logn, so extract k times, ideas 7 need K*logn. And this idea only need k^2). The complexity of this method is O (n+k^2). This method may be less intuitive, and a more intuitive understanding is that the nature of the minimum heap is destroyed every time the heap top element is removed, and we need to adjust the minimum heap to satisfy the minimum heap nature. Since we only need to ask for the first k number, we do not need to complete the entire heap adjustment, just to ensure that the top K number of the heap is the smallest can be, that is, the first adjustment to maintain the No. 0 layer to the K-level is the smallest heap, the second adjustment to maintain the No. 0 layer to the first k-1 layer is the smallest heap ...

Before you encode this idea, you might want to understand: quick sorting, heap ordering.

One implementation of IDEA 3:

1#include <stdio.h>2#include <stdio.h>3#include <stdlib.h>4 #definePARENT (i) (i)/25 #defineLeft (i) +1 (i)6 #defineRight (i) (i+1)7  8 voidSwapint*a,int*b)9 {Ten*a=*a^*b;  One*b=*a^*b;  A*a=*a^*b;  - } - voidMax_heapify (int*arr,intIndexintlen) the { -     intL=Left (index); -     intR=Right (index); -     intlargest; +     if(L<len && arr[l]>Arr[index]) -largest=l; +     Else Alargest=index; at     if(R<len && arr[r]>Arr[largest]) -largest=R; -     if(Largest! = index) {//raise the maximum element and recursively -Swap (&arr[largest],&Arr[index]); - max_heapify (Arr,largest,len); -     } in } -   to voidBuild_maxheap (int*arr,intlen) + { -     inti; the     if(Arr==null | | len<=1) *         return; $      for(i=len/2+1; i>=0;--i)Panax Notoginseng max_heapify (Arr,i,len); - } the   + voidK_min (int*arr,intLenintk) A { the     inti; + build_maxheap (arr,k); -      for(i = K;i < len;i++) $     { $         if(Arr[i] < arr[0]) -         { -arr[0] =Arr[i]; theMax_heapify (arr,0, k); -         }Wuyi     } the } - /* Wu void heap_sort (int *arr,int len) - { About int i; $ if (arr==null | | len<=1) - return; - build_maxheap (Arr,len); -      A For (i=len-1;i>=1;--i) { + swap (&arr[0],&arr[i]); the max_heapify (arr,0,--len); -     } $ } the */ the   the   the intMain () - { in     intarr[Ten]={ the,8,6, the, the, -,7, $, in, A}; the     inti; theK_min (arr,Ten,4); About      for(i=0;i<Ten;++i) theprintf"#df", Arr[i]); theSystem"Pause"); the}
Realization of Idea 4

First, the pseudo-code given in the beauty of programming is given:

1 Kbig (S, k):2      if(k <=0):  3           return[]//returns an empty array4      if(Length S <=k):5           returnS6(Sa, Sb) =Partition (S)7      returnKbig (Sa, K). Append (Kbig (Sb, k–length Sa)8   9 Partition (S):TenSa = []//initialize to an empty array OneSb = []//initialize to an empty array ASwap (s[1], S[random ()%length S])//randomly select a number as the grouping criterion to -                         //avoid the degradation of algorithms under special data, and can also -                        //to pass the entire data to the shuffle preprocessing the                         //for this purpose -p = s[1]   -       forIinch[2: Length S]: -S[i] > P?sa.append (S[i]): Sb.append (S[i]) +                             //adding p to smaller groups avoids grouping failures and also makes grouping -                            //more uniformity and improved efficiency +Length Sa < length Sb?Sa.append (P): Sb.append (P) A      return(Sa, Sb)

A simplified implementation is as follows:

#include <stdio.h>#include<stdlib.h>voidSwapint*a,int*b) {*a=*a^*b; *b=*a^*b; *a=*a^*C; }    /*For the sake of simplicity, this is just a simple selection of the first element as the pivot element.    This way, it is difficult to avoid making the algorithm easy to degenerate. */    intK_big (intArr[],intLowintHighintk) {intPivot =Arr[low]; intHigh_tmp =High ; intLow_tmp =Low ;  while(Low <High ) {            //right-to-left lookup until the first one less than the pivot element is found             while(Low < High && Arr[high] >=pivot) {                --High ; } Arr[low]=Arr[high]; //find from left to right until the first one is greater than the pivot element             while(Low < High && Arr[low] <=pivot) {                ++Low ; } Arr[high]=Arr[low]; } Arr[low]=pivot; if(Low = = K-1)        {            returnArr[low]; }Else if(Low > K-1)        {            returnK_big (arr,low_tmp,low-1, K); }Else        {            returnK_big (arr,low+1, high_tmp,k); }    }    intMain () {intarr[Ten]={- the,0,6, the, the, -,7, $,- in, A}; inti; K_big (arr,0,9,4);  for(i=0;i<Ten;++i) printf ("%d", Arr[i]); System ("Pause"); } 

Code Source: http://www.cricode.com/968.html

Sort, ask for a few of the most value problems, enter n integers, and output the smallest of the k elements.

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.