Java heap sorting instances (large top heap and small top heap) and java heap sorting instances

Source: Internet
Author: User

Java heap sorting instances (large top heap and small top heap) and java heap sorting instances

Heapsort)It is a sort algorithm designed by using the data structure such as heap. Accumulation is a structure that is similar to a Complete Binary Tree and meets the accumulation nature: that is, the key value or index of a child node is always smaller than (or greater than) its parent node.

The average time complexity of heap sorting is commit (nlogn ).

Algorithm steps:

1. Create a heap H [0 .. n-1]

2. Swap the beginning (maximum) and end of the heap

3. Reduce the heap size by 1 and call shift_down (0) to adjust the top data of the new array to the corresponding position.

4. Repeat Step 2 until the heap size is 1

Heap:

A heap is actually a Complete Binary Tree. Any non-leaf node of the heap satisfies the following requirements: key [I] <= key [2i + 1] & Key [I] <= key [2i + 2] or Key [I]> = Key [2i + 1] & & key> = key [2i + 2] indicates that the keywords of any non-leaf node are not greater than or less than the keywords of the left and right child nodes. A heap is divided into a large heap and a small heap. The heap meets the requirements of Key [I]> = Key [2i + 1] & key> = key [2i + 2, meeting Key [I] <= key [2i + 1] & Key [I] <= key [2i + 2] is called a small top heap. From the above properties, we can see that the keywords of the heap top of the big top stack must be the largest among all keywords. the keywords of the heap top of the small top stack are the smallest of all keywords.

Heap sorting thought:

The largest keyword (minimum keyword) is recorded on the top of a large (small top heap) stack, making it easy to select the maximum record (minimum record) from disorder each time. The basic idea is (Big Top heap): 1) sequence of the initial keywords to be sorted (R1, R2 .... Rn) build a large top heap, which is the initial unordered zone; 2) exchange the top element R [1] with the last element R [n, in this case, a new unordered partition (R1, R2 ,...... Rn-1) and the new ordered zone (Rn), and meet R [1, 2... n-1] <= R [n]; 3) because the new stack top R [1] After switching may violate the stack nature, the unordered zone (R1, R2, ...... Rn-1) adjusted to the new heap, and then re-swap the R [1] with the last element of the unordered area, get the new unordered area (R1, R2 .... Rn-2) and the new ordered zone (Rn-1, Rn ). Repeat this process until the number of elements in the ordered area is n-1, the entire sorting process is completed. The procedure is as follows: 1) initialize the heap: Set R [1 .. n] is constructed as a heap. 2) swap the top element R [1] In the unordered zone with the last record in the interval, and then adjust the unordered zone to the new heap. Therefore, the two most important operations for heap sorting are the construction of the initial heap and the adjustment of the heap. In fact, the construction of the initial heap is also the process of adjusting the heap, however, when the initial heap is constructed, all non-leaf nodes are adjusted.

Example

Heap sorts an integer array a [] = {16, 7, 3, 20, 17,8. First, construct a Complete Binary Tree Based on the array element.

Then, you need to construct the initial heap and adjust it from the last non-leaf node. The adjustment process is as follows:

After switching between 20 and 16, 16 does not meet the nature of the heap, so it needs to be adjusted again.

In this way, the initial heap is obtained.

When one adjustment is made,

That is, each adjustment selects the parent node from the parent node, the left child node, and the right child node to exchange with the parent node (after the switch, the child node to be exchanged may not meet the nature of the heap, therefore, after each switch, you must re-adjust the child node to be switched ). With the initial heap, you can sort it.

At this time, 3 is located at the top of the heap and is not satisfied with the nature of the heap, you need to adjust it to continue the adjustment

In this way, the entire interval is sorted. From the above process, we can see that heap sorting is actually a kind of selection sorting, and a kind of tree selection sorting. In order to directly select the sort... n] to select the maximum record, you need to compare n-1 times, and then from R [1... select the maximum record in N-2] to compare the N-2 times. In fact, many of the N-2 comparison has already done in the first n-1 comparison, and the tree selection and sorting just uses the characteristics of the tree to save some of the previous comparison results, so you can reduce the number of comparisons. For n keyword sequences, each node needs to compare log2 (n) times in the worst case. Therefore, the time complexity in the worst case is nlogn. The heap sorting is unstable and is not suitable for sorting with fewer records. As described above, in short, the basic method of heap sorting is: first, build a large (small) heap with the raw data as the original unordered zone, and then retrieve the top element of the heap each time, in the ordered area. Since the heap top element is taken out, we put the last element in the heap into the heap top, so that the nature of the heap will be destroyed. We need to re-adjust the heap, so that we continue N times, then the N elements in the unordered area are put into the ordered area, and the sorting process is completed.
(The heap is built from the bottom up)

Practical application:

In practice, we sort the heap to obtain the maximum or minimum values under certain conditions. For example, we need to find the 10 maximum values in the 100 count. Therefore, we define a heap with a size of 10, create the first 10 Data in 100 into a small top heap (minimum heap top), and compare the data with the top 100 data. If the top of the heap is smaller than the current data, in this case, the heap top pops up, the current data is pushed to the heap top, and the data is moved from the bottom of the heap to a certain position,

Code:

Public class Test0 {static int [] arr; // heap array, valid array public Test0 (int m) {arr = new int [m];} static int m = 0; static int size = 0; // used to mark valid data in the heap public void addToSmall (int v) {// int [] a =, 13, 14, 15, 2, 3, 6, 7, 8, 111,222,333,555, 54}; // The heap size is 10 // arr = new int [10]; if (size <arr. length) {arr [size] = v; add_sort (size); // add_sort1 (size); size ++;} else {arr [0] = v; add_sort1 (0) ;}} public void printSmall () {for (I Nt I = 0; I <size; I ++) {System. out. println (arr [I]) ;}} public void del () {size --; arr [0] = arr [9]; add_sort1 (0 );} public void Small (int index) {if (m <arr. length) {add_sort (index); m ++;} else {add_sort1 (index); m ++ ;}} public void add_sort (int index) {// small top heap, heap creation/** parent node coordinate: index * left child node: index * 2 * right child node: index * 2 + 1 * If the last in the array is an odd number, it is the left child * If the last in the array is an even number, it is the right child. If the child node is larger than the parent node, the value is exchanged. if the right child is greater than the left child, the value is exchanged. **/int par; if (index! = 0) {if (index % 2 = 0) {par = (index-1)/2; if (arr [index] <arr [par]) {swap (arr, index, par); add_sort (par);} if (arr [index]> arr [par * 2]) {swap (arr, index, par * 2); if (arr [index] <arr [par]) {swap (arr, index, par) ;}add_sort (par );}} else {par = index/2; if (arr [index] <arr [par]) {swap (arr, index, par); add_sort (par );} if (arr [index] <arr [par * 2 + 1]) {swap (arr, index, par * 2 + 1 ); if (arr [index] <arr [par]) {swap (arr, index, par) ;}add_sort (par) ;}}} publi C void add_sort1 (int index) {// adjust the small top Heap/* adjust from top to bottom * as long as the value of the child node is greater than that of the parent node, the value is exchanged, */int left = index * 2; int right = index * 2 + 1; int max = 0; if (left <10 & arr [left] <arr [index]) {max = left;} else {max = index;} if (right <10 & arr [right] <arr [max]) {max = right;} if (max! = Index) {swap (arr, max, index); add_sort1 (max) ;}} test code: package Big Top heap; import java. util. secret; public class Main_test0 {public static void main (String args []) {shortscan = new role (System. in); System. out. println ("(small top heap) enter the heap size:"); int m = scan. nextInt (); Test0 test = new Test0 (m); int [] a = }; for (int I = 0; I <. length; I ++) {test. addToSmall (a [I]);} test. printSmall (); test. del (); test. printSmall (); scan. close ();}}

The above Java heap sorting example (Big Top heap and small top heap) is all the content shared by the small editor. I hope to give you a reference and support for the customer's house.

Related Article

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.