Several Solutions algorithm Top of

First, the global ordering

  Any sorting algorithm can be, but the time complexity or space complexity degree does not meet the requirements. Obviously only TopK, sorting puts globally, and this is the complexity of this method very high reasons. That can not but globally ordered, but only partial ordering it? This leads to the second method of optimizing a partial ordering .

Second, local sorting

  (1) bubble sort: take each of a bubble, to find the maximum value, take a bubble k, is obtained TopK

     Fake code:

        for(i=1 to k){
          bubble_find_max(arr,i);
        }

  Bubble sort, the sort For topical global ordering optimization, the element is not required TopK non sorted, save computational resources, time complexity of O (n * k). Many of my friends will think, demand is TopK, is not this the largest k elements do not need to sort it? This leads to a third optimization heap sort .

Third, heap sort

  Ideas: only found TopK, not the sort TopK.

  Step a: before generating the first k elements of a small pile top, the top of the heap for storing small, the current maximum of k elements.

  Step two: Starting from the first scan k + 1 elements, and the top of the stack (the smallest element in the stack), and if the top of the stack is greater than the scan element, the top element of the stack is replaced, and adjusting the stack, to ensure that the stack k elements, always current maximum of k elements.

   Step Three: nk scanning of all the elements, the final stack k elements, i.e., to obtain TopK.

  Time complexity: O (n * lg (k))

  Fake code:

    heap[k] = make_heap(arr[1, k]);
      for(i=k+1 to n){
      adjust_heap(heep[k],arr[i]);
    }
    return heap[k];

=>=>  

Guess you like

Origin www.cnblogs.com/hdc520/p/12099203.html