zoukankan      html  css  js  c++  java
  • 堆排序宇宙最简单版本

     1 package com.array;
     2 
     3 import java.util.Arrays;
     4 
     5 public class HeapSort {
     6     public static void main(String[] args) {
     7         int[] a = {45,14,5,24,5,62,7,84,34,14};
     8         buildHeap(a);
     9 
    10         System.out.println(Arrays.toString(a));
    11         heapSort(a);
    12         System.out.println(Arrays.toString(a));
    13     }
    14     public static void heapSort(int[] arr) {
    15         buildHeap(arr);
    16         for (int i = arr.length - 1; i >= 0; i--) {
    17             swap(arr, 0, i);
    18             heapfy(arr, 0, i-1);
    19         }
    20     }
    21 
    22     public static void buildHeap(int[] arr) {
    23         for (int i = arr.length / 2 - 1; i >= 0; i--) {
    24             heapfy(arr, i, arr.length - 1);
    25         }
    26     }
    27 
    28     public static void heapfy(int[] arr, int root, int limit) {
    29         int lson = 2 * root + 1;
    30         int rson = 2 * root + 2;
    31         int temp;
    32         if (lson <= limit && rson <= limit) {
    33             temp = arr[lson] > arr[rson] ? lson : rson;
    34         } else if (lson <= limit) {
    35             temp = lson;
    36         } else if (rson <= limit) {
    37             temp = rson;
    38         } else return;
    39 
    40         if (arr[temp] > arr[root]) {
    41             swap(arr, temp, root);
    42             heapfy(arr, temp, limit);
    43         }
    44     }
    45 
    46 
    47     public static void swap(int[] arr, int i, int j) {
    48         int temp = arr[i];
    49         arr[i] = arr[j];
    50         arr[j] = temp;
    51     }
    52 }
  • 相关阅读:
    一站式学习Wireshark第六章
    一站式学习Wireshark第七章
    一站式学习Wireshark第八章
    一站式学习Wireshark第九章
    一站式学习Wireshark第十章
    一站式学习Wireshark第一章
    第二周的学习进度
    架构漫谈随笔
    淘宝网描绘质量属性六个常见属性场景
    二月十五日
  • 原文地址:https://www.cnblogs.com/tianyee/p/14925724.html
Copyright © 2011-2022 走看看