Heap

堆和堆排序, update@20210105

最大堆(max heap)的实现

import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;

/**
 * max heap
 *
 * @author fangchao
 */
public class Heap {
    private ArrayList<Integer> list = new ArrayList<>();

    public Heap() {
        list.add(null);
    }

    public void print() {
        System.out.println(list.toString());
    }

    public void add(Integer integer) {
        list.add(integer);
        int index = list.size() - 1;
        heapIt(index);
    }


    private void heapIt(int index) {
        int parent;
        while ((parent = index / 2) > 0) {
            int p = list.get(parent);
            int c = list.get(index);
            if (p < c) {
                list.set(parent, c);
                list.set(index, p);
                index = parent;
            } else {
                break;
            }
        }
    }

    public static void main(String[] args) {

        int size = 15;
        int min = 1;
        int max = 10;
        int testNum = 100;
        for (int j = 0; j < testNum; j++) {
            Heap heap = new Heap();
            for (int i = 0; i < size; i++) {
                int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
                heap.add(randomNum);
            }
            heap.print();
        }
    }
}

Read list:

Search

    Categories Cloud

    Life Linux C/CPP Database Web Benchmarks Software Data Python TCP/IP Financial Stock Bug Golang Rust General Infrastructure TODO Movie Multitenancy Java Ant Algorithm Fastjson Death Build Deploy Education India Aamir Khan Society Female Learning Method OJ Interviewee Interviewer AVL Tree MyBatis Code Reading Design Diary Dating Heap Data Structure Summary Reading Love Claire Mcfall Ferryman Zodiac Astrology Chinese Calculator flink Dubbo docker redis

    Table of Contents