Daily algorithm ———— heap sorting

Source: Internet
Author: User

Today sorted out the next heap sort, to an outsider's identity re-organized the heap sort (previously learned to forget) heap sorting based on the binary tree, review the binary tree, heap sorting is not difficult to write.

or the code.

 Packagearithmetic;Importjava.util.Arrays; Public classHeapsort { Public Static voidMain (string[] args) {int[] arr = {9, 8, 7, 6, 5, 4, 3, 2, 1 };        Sort (arr);    System.out.println (arrays.tostring (arr)); }     Public Static voidSortint[] arr) {        //1. Build a large top heap         for(inti = ARR.LENGTH/2-1; I >= 0; i--) {            //adjusts the structure from the first non-leaf node from bottom to top, right to left .adjustheap (arr, I, arr.length); }        //2. Adjusting the heap structure + Exchange heap top element and end element         for(intj = arr.length-1; J > 0; j--) {swap (arr,0, J);//swap the top element of the heap with the end elementAdjustheap (arr, 0, J);//to re-adjust the heap        }    }     Public Static voidAdjustheap (int[] arr,intIintlength) {        inttemp = Arr[i];//first remove the current element I         for(intK = i * 2 + 1; K < length; K = k * 2 + 1) {//Starting at the left Dial hand node of the I node, which is 2i+1 .            if(k + 1 < length && Arr[k] < Arr[k + 1]) {//If the left Dial hand node is small less right operand sub-node, K points to the right child node .k++; }            if(Arr[k] > Temp) {//assigns the child node value to the parent node if the child node is larger than the parent node (no swapping)Arr[i] =Arr[k]; I= k;//nodes that hold larger values}Else {                 Break; }} Arr[i]= temp;//put the temp value in the final position    }    //Exchanging Data     Public Static voidSwapintArr[],intAintb) {inttemp =Arr[a]; Arr[a]=Arr[b]; ARR[B]=temp; }}

Daily algorithm ———— heap sorting

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.