Heap sort java implementation

1  import java.util.Arrays;
 2  
3  /* 
4  * Ideas:
 5  * 1. Method adjustDown: For an array a[], adjust downward (until len-1) for the ith number, so that the position becomes Big top heap
 6  * 2. Method bulidMaxHeap: from len/2-1 position to 0 position, call adjustDown cyclically to make it a big top heap
 7  * 3. Method heapSort: build a large top heap, let the first and the last one Switch positions, then adjustDown the first one. cycle.
8   */ 
9  public  class HeapSort {
 10      // Build a large top heap 
11      public  static  void buildMaxHeap( int [] a) {
 12          for ( int i=(a.length/2)-1;i>=0;i- - ) {
 13             adjustDown(a,i,a.length);
 14          }
 15      }
 16      // Adjust down 
17      public  static  void adjustDown( int [] a, int i, int len) {
 18          int temp,j;
 19          temp= a[ i];
 20          for (j=2*i+1;j<len;j=2*j+1) {        // j is the child node of the current i, the default is the left node 
21              if (j+1<len&&a[ j+1]>a[j])        // If the right node is large, select the right node 
22                  j++ ;
 23              if (a[j]<=temp)                 // If     the child nodes are smaller than the initial value temp, it means that the position 
24 is found.                  break ;
 25              else {                           
 26                  a[i]=a[j]                    ; 27                  i=j;                        // At the same time i drops to the position of j 28             }
 29         }
 30          a[i]=temp;                            // put temp in the final position 31     }
 32 // heap sort 33 public static void heapSort( int [ ] a) {
 34

  
      
                buildMaxHeap(a);
 35          for ( int i=a.length-1;i>=0;i-- ) {
 36              int temp=a[0 ];
 37              a[0]= a[i];
 38              a[ i]= temp;
 39              adjustDown(a,0,i);   // Adjust the remaining len-1 to a large top heap, loop, so use i to represent 
40          }
 41      }
 42      public  static  void main(String[] args) {
 43          int [] a= {5,88,45,37,91,26,13,66,50 };
 44          heapSort(a);
 45          System.out.println(Arrays.toString(a));
46     }
47 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325265683&siteId=291194637