[Big, small Gan application Summary One] heap sort of application scenario

Source: Internet
Author: User

Objective

In the collation of the algorithm, it is found that the data structure of Dagen (Keng Gen) is widely used in various algorithms, typical heap ordering, and using the data structure of the size root heap to find an optimal solution to the problem. Therefore, I intend to separate the application of the heap separately from each application that is associated with a heap structure that is placed in this directory.

Definition of a heap

n keyword sequence L[1...N] is called a heap when and only if the sequence satisfies:
1. L (i) <=l (2i) and L (i) <=l (2i+1) or
2. L (i) >=l (2i) and L (i) >=l (2i+1)
Satisfies the first condition becomes small Gan (that is, each node value is less than its left and right child node value), satisfies the second addition to become Dagen (i.e. each node value is greater than its left and right child node value).

Application one: The ordering of a basic ordered array, which sorting algorithm to choose?

Basic order: If the array is ordered, each element moves no more than K, and K is small relative to the array length.

Analysis 1, for the time complexity of O (N) sorting algorithm:

The algorithm of Time Complexity O (N) has cardinal sort, counting sort, but both of them need to know the range of the elements in advance so as to build the number of buckets, so it is not appropriate to solve this problem. Exclude!

2, for the time complexity of O (N2) sorting algorithm:

Time complexity O (N2) commonly used mainly bubble, select, insert, linked to the topic of the basic order, the insertion sort is preferred, each element moving distance not more than k, so the insertion of the order of each element moving forward is not more than K, so when the insertion sort time complexity of O (n*k), So the insertion sort can be taken into consideration.

3, for the time complexity of O (N*LOGN) sorting algorithm

Time complexity O (N2) is commonly used for fast sorting, merge sorting, heap sorting, because these two sorting methods are not related to the initial order of the array elements, so these two methods are also a good one. Heap sequencing is O (N*LOGN) at the best, worst, and average time complexity.

Better solution

Based on the above analysis, we initially locked in the time complexity of O (N*LOGN) sorting algorithm.
1. Again according to test instructions, each element will not move more than K, indicating that the first k elements must have the smallest element in the array, that is, array[0]~array[k-1] there is a minimum element, from which to take the smallest element, then move back one step, that is, the array array[1] ~array[k] There is a minor element that goes down ... You can get n-k elements, and finally sort the last k elements.
2. Therefore, we can first set up a K-element of the small Gan, each time to take out the top of the heap, and then move back a small Gan to adjust, loop down ... The last K-elements therefore narrow the range of adjustment again. The code is as follows:

 Public Static int[]Heapsort(int[] A,intNintK) {if(A = =NULL|| A.length = =0|| N < k) {return NULL; }int[] heap =New int[K]; for(inti =0; I < K;          i++) {Heap[i] = A[i]; } buildminheap (Heap,k);//Build a small heap first         for(inti = k; I < n; i++) {A[i-k] = heap[0];//difficulty heap top minimum elementheap[0] = A[i]; Adjust (heap,0, k); } for(inti = N-k;i < n; i++) {A[i] = heap[0]; heap[0] = heap[k-1]; Adjust (heap,0,--k);//Reduce the range of adjustments}returnA }//Build a small Gan    Private Static void Buildminheap(int[] A,intLen) { for(inti = (len-1) /2; I >=0;          i--) {adjust (A,i,len); }      }//downward adjustment, making the property of re-compounding small Gan    Private Static void Adjust(int[] A,intKintLen) {inttemp = A[k]; for(inti =2* k +1; i < Len; i = i *2+1){if(I < Len-1&& a[i+1] < A[i])//If there is a right child node, and the right child node value is less than the left Haizi node value .i++;//Fetch K subscript for smaller sub-nodes            if(temp <= a[i]) Break;//filter end, no downward adjustment            Else{//need to be adjusted downwardsA[K] = A[i]; K = i;//k point to the new node that needs to be adjusted}} A[k] = temp;//The value of this trip needs to be adjusted finally to the last need to adjust the node at the point}
Analysis of time complexity

The time complexity of re-establishing the heap in each of the K elements in the heap is related to the height of the heap, O (logk), n elements are adjusted, the time complexity is O (n), so the total time complexity is O (NLOGK), because K is smaller relative to the array length n, So this method of sorting using small Gan is relatively superior to the quick sort and merge sort of O (Nlogn).

Application two: Determine whether there are duplicate values in the array, requiring the space complexity of O (1)? Idea One

If there is no spatial complexity limit, it can be implemented with a hash table. For example, using HashMap, the data element is saved to the key value, before each save to determine whether the existence of the key value, if there is a duplicate value of the description. At this point, the time complexity is O (n) and the spatial complexity is O (n). The code is as follows:

/** * Using HashMap to Achieve * @param A * @param n * @return  * *     Public Static Boolean Checker2(int[] A,intN) {if(A = =NULL|| A.length = =0|| A.length = =1)return false; map<integer,integer> map =NewHashmap<integer,integer> (); for(inti =0; I < n; i++) {if(Map.containskey (A[i]))return true; Map.put (A[i],1); }return false; }
Two ideas
  1. For the limitations of space complexity, we can first sort, then Judge the idea. Because of the order, duplicate values are placed in adjacent positions. At this point, the problem is converted to, the space complexity is limited to O (1) case, the study of the classical sorting algorithm, how to achieve a fastest algorithm.
  2. The space complexity is O (1) with bubbling, selection, insertion, hill sort, and non-recursive heap ordering, and then judging by the time complexity, the heap ordering is O (NLOGN), you can know that the use of non-recursive implementation of the heap sorting the fastest.
    The step at this point is to sort the array by the heap order, and then iterate through the array to compare the values of the adjacent two elements as equal. The code is as follows:
 Public Static Boolean checkduplicate(int[] A,intN) {if(A = =NULL|| A.length = =0|| A.length = =1)return false; Heapsort (A,n); for(inti =1; I < n; i++) {if(A[i] = = a[i-1]){return true; }        }return false; }Private Static void Heapsort(int[] A,intN) { for(inti = (n1) /2; I >=0;        i--) {Adjustdown (a,i,n); }intTemp for(inti = n1; i >0; i--) {//Only need n-1 triptemp = a[0];//Exchange heap top elementa[0] = A[i];            A[i] = temp; Adjustdown (A,0, i); }    }Private Static void Adjustdown(int[] A,intKintN) {inttemp = A[k]; for(inti =2* k +1; I < n; i = i *2+1){if(I < n1&& A[i] < a[i+1])//Have right child node, and have child node value is greater than left Haizi node value, will I point to right child .i++;if(temp >= a[i]) Break;Else{//requires downward adjustmentA[K] = A[i]; K = i;//point to new nodes that may need to be adjusted}} A[k] = temp; }
Time Complexity Analysis:

Heap sequencing has a time complexity of O (Nlogn), followed by only one traversal, so the total time complexity is O (NLOGN).

以上就是堆应用的两个场景,后面碰到了,继续总结。。。

[Big, small Gan application Summary One] heap sort of application scenario

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.