Home Java javaTutorial Examples of heaps of bases for algorithm design and analysis

Examples of heaps of bases for algorithm design and analysis

Jul 24, 2017 pm 01:17 PM
analyze Base design

Use array to store heap data

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

package cn.xf.algorithm.ch06ChangeRule;

  

import java.util.ArrayList;

import java.util.List;

  

import org.junit.Test;

  

/**

 *

 * 功能:堆的构造

 * 1、堆可以定义为一颗二叉树,树的节点包含键,并且满足一下条件

 *  1) 树的形状要求:这棵二叉树是基本完备的(完全二叉树),树的每一层都是满的,除了最后一层最右边的元素可能缺位

 *  2) 父母优势,堆特性,每一个节点的键都要大于或者等于他子女的键(对于任何叶子我们认为这都是自动满足的)

 *

 * 对于堆:

 *   只存在一颗n个节点的完全二叉树他的高度:取下界的 log2的n的对数

 *  堆的根总是包含了堆的最大元素

 *  堆的一个节点以及该节点的子孙也是一个堆

 *  可以用数组的来实现堆,方法是从上到下,从左到右的方式来记录堆的元素。

 * @author xiaofeng

 * @date 2017年7月9日

 * @fileName Heap.java

 *

 */

public class Heap {

    /**

     * 堆的数据存放结构

     */

    private List<Double> heap;

  

    /**

     * 自下而上构建一个堆

     */

    private List<Double> createHeadDownToUp(List<Double> heap) {

        if(heap == null || heap.size() <= 0)

            return heap;

          

        //数据个数

        int nums = heap.size();

        //吧数组整体后移一位,方便数据的计算,因为从0开始,那么2*0还是0,没有体现出2*n就是n的左孩子的基本设定

        heap.add(0, 0d);

          

        //构建一个堆,从数组的中间位置开始,因为中间位子mid的两倍正好差不多是这个树的末尾,而在这个2*mid的附近就是mid这个节点的孩子节点

        for(int i = nums / 2 + 1; i > 0; --i) {

            //获取基准节点的地址

            int baseIndex = i;

            //获取这个节点的值

            double vBaseValue = heap.get(baseIndex);

            boolean isHeap = false; //这个用来判断当前遍历的这三个数字是否满足堆的概念

            //进行堆变换,交换树的节点和孩子节点数值,使当前树满足堆的概念

            //2 * baseIndex <= nums 这个用来判断这颗树的子树也满足堆的定义

            while(!isHeap && 2 * baseIndex <= nums) {

                //获取当前遍历到的数据的左孩子节点的位置

                int maxChildIndex = 2 * baseIndex;

                //从两个孩子节点中获取大的那个位置

                if(maxChildIndex < nums) {

                    //如果左孩子的位置比总长还小,由于完全二叉树的属性,那么必定存在右孩子节点

                    //判断那个孩子节点的数据比较大,使max为大的那个

                    if(heap.get(maxChildIndex) < heap.get(maxChildIndex + 1)) {

                        //如果右孩子比较大

                        maxChildIndex += 1;

                    }

                }

                  

                //再判断,当前 节点的值是不是比孩子节点的值要大,如果是那么就当前子树是满足堆的属性

                //maxChildIndex == nums  那还是瞒住条件,可以进行左子树的比较

                if(maxChildIndex > nums || vBaseValue >= heap.get(maxChildIndex)) {

                    isHeap = true;

                } else {

                    //如果不满住,那么交换,吧大的数据交换到节点上,吧节点的数据换到孩子节点上

                    heap.set(baseIndex, heap.get(maxChildIndex));

                    baseIndex = maxChildIndex;

                    heap.set(baseIndex, vBaseValue);

                }

            }

        }

          

        //去除第一个0,然后返回

        heap.remove(0);

        return heap;

    }

      

    private void shifHeadDownToUp(int i) {

        if (heap == null || heap.size() <= 0)

            return;

          

        // 数据个数

        int nums = heap.size();

        // 吧数组整体后移一位,方便数据的计算,因为从0开始,那么2*0还是0,没有体现出2*n就是n的左孩子的基本设定

        heap.add(0, 0d);

        boolean isHeap = false;

        int baseIndex = i;

        double vBaseValue = heap.get(i);

        while (!isHeap && 2 * baseIndex <= nums) {

            // 获取当前遍历到的数据的左孩子节点的位置

            int maxChildIndex = 2 * baseIndex;

            // 从两个孩子节点中获取大的那个位置

            if (maxChildIndex < nums) {

                // 如果左孩子的位置比总长还小,由于完全二叉树的属性,那么必定存在右孩子节点

                // 判断那个孩子节点的数据比较大,使max为大的那个

                if (heap.get(maxChildIndex) < heap.get(maxChildIndex + 1)) {

                    // 如果右孩子比较大

                    maxChildIndex += 1;

                }

            }

              

            // 再判断,当前 节点的值是不是比孩子节点的值要大,如果是那么就当前子树是满足堆的属性

            // maxChildIndex == nums 那还是瞒住条件,可以进行左子树的比较

            if (maxChildIndex > nums || vBaseValue >= heap.get(maxChildIndex)) {

                isHeap = true;

            } else {

                // 如果不满住,那么交换,吧大的数据交换到节点上,吧节点的数据换到孩子节点上

                heap.set(baseIndex, heap.get(maxChildIndex));

                baseIndex = maxChildIndex;

                heap.set(baseIndex, vBaseValue);

            }

        }

          

        // 去除第一个0,然后返回

        heap.remove(0);

    }

      

    //创建堆

    public Heap() {

        heap = new ArrayList<Double>();

        createHeadDownToUp(heap);

    }

      

    public Heap(List<Double> data) {

        if(data == null || data.size() <= 0) {

            data = new ArrayList<Double>();

        }

        heap = data;

        createHeadDownToUp(heap);

    }

      

    @Override

    public String toString() {

        return heap.toString();

    }

      

    public void add(Double value) {

        if(value == null)

            return;

        heap.add(value);

//      int insertInedx = heap.size();

        //自底向上构建堆

        for(int i = heap.size() / 2; i >= 0; --i) {

            shifHeadDownToUp(i + 1);

        }

    }

      

      

    /**

     * 删除一个元素,获取这个元素的索引位置来删除

     * 1、根的键《和》堆的最后一个键K做交换

     * 2、堆的规模减一

     * 3、严格按照自底向上的够着算法的做法,吧K 向下筛选,堆数据进行堆化

     * @param index

     */

    public void delete(int index) {

        //这个是自底向上进行堆化数据

        //吧最后一个数据填入到要删除的数据中

        Double lastValue = heap.get(heap.size() - 1);

        //删除最后一个元素,吧最后一个元素用来取代这个需要删除的元素

        heap.set(index, lastValue);

        heap.remove(heap.size() - 1);

        //自底向上开始堆化

        for(int i = index; i >= 0; --i)

            shifHeadDownToUp(i + 1);

    }

      

}

Copy after login


The above is the detailed content of Examples of heaps of bases for algorithm design and analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZTE 5G portable Wi-Fi U50S goes on sale for NT$899 at first launch: top speed 500Mbps ZTE 5G portable Wi-Fi U50S goes on sale for NT$899 at first launch: top speed 500Mbps Apr 26, 2024 pm 03:46 PM

According to news on April 26, ZTE’s 5G portable Wi-Fi U50S is now officially on sale, starting at 899 yuan. In terms of appearance design, ZTE U50S Portable Wi-Fi is simple and stylish, easy to hold and pack. Its size is 159/73/18mm and is easy to carry, allowing you to enjoy 5G high-speed network anytime and anywhere, achieving an unimpeded mobile office and entertainment experience. ZTE 5G portable Wi-Fi U50S supports the advanced Wi-Fi 6 protocol with a peak rate of up to 1800Mbps. It relies on the Snapdragon X55 high-performance 5G platform to provide users with an extremely fast network experience. Not only does it support the 5G dual-mode SA+NSA network environment and Sub-6GHz frequency band, the measured network speed can even reach an astonishing 500Mbps, which is easily satisfactory.

Retro trend! HMD and Heineken jointly launch flip phone: transparent shell design Retro trend! HMD and Heineken jointly launch flip phone: transparent shell design Apr 17, 2024 pm 06:50 PM

According to news on April 17, HMD teamed up with the well-known beer brand Heineken and the creative company Bodega to launch a unique flip phone - The Boring Phone. This phone is not only full of innovation in design, but also returns to nature in terms of functionality, aiming to lead people back to real interpersonal interactions and enjoy the pure time of drinking with friends. Boring mobile phone adopts a unique transparent flip design, showing a simple yet elegant aesthetic. It is equipped with a 2.8-inch QVGA display inside and a 1.77-inch display outside, providing users with a basic visual interaction experience. In terms of photography, although it is only equipped with a 30-megapixel camera, it is enough to handle simple daily tasks.

Honor Magic V3 debuts AI defocus eye protection technology: effectively alleviates the development of myopia Honor Magic V3 debuts AI defocus eye protection technology: effectively alleviates the development of myopia Jul 18, 2024 am 09:27 AM

According to news on July 12, the Honor Magic V3 series was officially released today, equipped with the new Honor Vision Soothing Oasis eye protection screen. While the screen itself has high specifications and high quality, it also pioneered the introduction of AI active eye protection technology. It is reported that the traditional way to alleviate myopia is "myopia glasses". The power of myopia glasses is evenly distributed to ensure that the central area of ​​​​sight is imaged on the retina, but the peripheral area is imaged behind the retina. The retina senses that the image is behind, promoting the eye axis direction. grow later, thereby deepening the degree. At present, one of the main ways to alleviate the development of myopia is the "defocus lens". The central area has a normal power, and the peripheral area is adjusted through optical design partitions, so that the image in the peripheral area falls in front of the retina.

Teclast M50 Mini tablet is here: 8.7-inch IPS screen, 5000mAh battery Teclast M50 Mini tablet is here: 8.7-inch IPS screen, 5000mAh battery Apr 04, 2024 am 08:31 AM

According to news on April 3, Taipower’s upcoming M50 Mini tablet computer is a device with rich functions and powerful performance. This new 8-inch small tablet is equipped with an 8.7-inch IPS screen, providing users with an excellent visual experience. Its metal body design is not only beautiful but also enhances the durability of the device. In terms of performance, the M50Mini is equipped with the Unisoc T606 eight-core processor, which has two A75 cores and six A55 cores, ensuring a smooth and efficient running experience. At the same time, the tablet is also equipped with a 6GB+128GB storage solution and supports 8GB memory expansion, which meets users’ needs for storage and multi-tasking. In terms of battery life, M50Mini is equipped with a 5000mAh battery and supports Ty

How to design the end page of ppt to be attractive enough How to design the end page of ppt to be attractive enough Mar 20, 2024 pm 12:30 PM

At work, ppt is an office software often used by professionals. A complete ppt must have a good ending page. Different professional requirements give different ppt production characteristics. Regarding the production of the end page, how can we design it more attractively? Let’s take a look at how to design the end page of ppt! The design of the ppt end page can be adjusted in terms of text and animation, and you can choose a simple or dazzling style according to your needs. Next, we will focus on how to use innovative expression methods to create a ppt end page that meets the requirements. So let’s start today’s tutorial. 1. For the production of the end page, any text in the picture can be used. The important thing about the end page is that it means that my presentation is over. 2. In addition to these words,

Vivo's phone with the strongest signal! vivo X100s is equipped with a universal signal amplification system: 21 antennas, 360° surround design Vivo's phone with the strongest signal! vivo X100s is equipped with a universal signal amplification system: 21 antennas, 360° surround design Jun 03, 2024 pm 08:41 PM

According to news on May 13, vivoX100s was officially released tonight. In addition to excellent images, the new phone also performs very well in terms of signal. According to vivo’s official introduction, vivoX100s uses an innovative universal signal amplification system, which is equipped with up to 21 antennas. This design has been re-optimized based on the direct screen to balance many signal requirements such as 5G, 4G, Wi-Fi, GPS, and NFC. This makes vivoX100s the mobile phone with the strongest signal reception capability in vivo’s history. The new phone also uses a unique 360° surround design, with antennas distributed around the body. This design not only enhances the signal strength, but also optimizes various daily holding postures to avoid problems caused by improper holding methods.

Honor X60i mobile phone is on sale starting from 1,399 yuan: visual quadrilateral OLED direct screen Honor X60i mobile phone is on sale starting from 1,399 yuan: visual quadrilateral OLED direct screen Jul 29, 2024 pm 08:25 PM

According to news on July 29, the Honor X60i mobile phone is officially on sale today, starting at 1,399 yuan. In terms of design, the Honor X60i mobile phone adopts a straight screen design with a hole in the center and almost unbounded ultra-narrow borders on all four sides, which greatly broadens the field of view. Honor X60i parameters Display: 6.7-inch high-definition display Battery: 5000mAh large-capacity battery Processor: Dimensity 6080 processor (TSMC 6nm, 2x2.4G A76+6×2G A55) System: MagicOS8.0 system Other features: 5G signal enhancement, smart capsule, under-screen fingerprint, dual MIC, noise reduction, knowledge Q&A, photography capabilities: rear dual camera system: 50 million pixels main camera, 2 million pixels auxiliary lens, front selfie lens: 8 million pixels, price: 8GB

New stacking process! Xiaomi MIX Fold 4 is equipped with Jinshajiang 'three-dimensional special-shaped' battery for the first time New stacking process! Xiaomi MIX Fold 4 is equipped with Jinshajiang 'three-dimensional special-shaped' battery for the first time Jul 20, 2024 am 03:20 AM

According to news on July 19, Xiaomi MIX Fold 4, the first flagship folding new phone, was officially released tonight and is equipped with a "three-dimensional special-shaped battery" for the first time. According to reports, Xiaomi MIX Fold4 has achieved a major breakthrough in battery technology and designed an innovative "three-dimensional special-shaped battery" specifically for folding screens. Traditional folding screen devices mostly use conventional square batteries, which have low space utilization efficiency. In order to solve this problem, Xiaomi did not use the common winding battery cells, but developed a new lamination process to create a new form of battery, which greatly improved the space utilization. Battery Technology Innovation In order to accurately alternately stack positive and negative electrode sheets and ensure the safe embedding of lithium ions, Xiaomi has developed a new ultrasonic welding machine and lamination machine to improve welding and cutting accuracy.

See all articles