Comparison of Heap and Java Objects

This blog will summarize the comparison method of data structure heap and objects in Java based on the existing knowledge. The following blog is only a summary of the personal learning process. It is a great honor to be helpful to all bloggers.
This blog will briefly introduce the application of the concept and principle of the heap, as well as several methods of comparing objects. I will only make a summary of my own, and make supplementary modifications later as I learn more.

Heap

concept

A heap is a special data structure, which is usually an array object that can be regarded as a complete binary tree. This is because the
heap is logically a complete binary tree , and physically it is stored in an array . The order in which the points are stored in the array is the layer order traversal order of the binary tree

Two points that a heap must satisfy

Large heap: the value of any node is greater than the value of the nodes in its subtree
insert image description here

Small heap: the value of any node is less than the value of the nodes in its subtree
insert image description here

Principle and Implementation

Adjust down:

Premise: Except for the node (node), the left and right subtrees of the entire heap have met the heap condition

Process (small heap as an example):

  1. Judging whether there is a child, if the node (node) is a leaf node, then the adjustment is over and
    judging whether there is a child —> judging whether there is a left child (left) (because it is a complete binary tree, if there is a right child (right), there must be a left child ( left), so directly judge whether there is a left child (left)) —> judge whether the subscript of the left child (left) is out of bounds in the stored array
  2. Determine the minimum value min of the left subtree (left) and the right subtree (right), if the value of the right subtree does not exist, directly assign the value of the left subtree to min
  3. Judging the size of min and node (node), if less than, the adjustment is over, otherwise exchange the positions of the two nodes
  4. Since the exchange destroys the heap structure below the node, it is adjusted downward again with the node as the node until the node is a leaf node or the value of node is smaller than the value of the left subtree and the right subtree. Looking back, each exchange is
    diagram
    actually If the degree of the node is +1, then the depth of the execution tree in the worst case of the whole process is times, that is, the time complexity is O(log(n))
//向下调整代码演示
public void shiftDown(int[] arr,int size,int index){
    
    
        int left = index*2 + 1;
        while(left< size){
    
    
            int min = left;
            int right = index*2+2;
            if(right < size){
    
    
                if(arr[right] < arr[left]){
    
    
                    min = right;
                }
            }
            if(min > arr[index]){
    
    
                break;
            }
            int t = arr[index];
            arr[index] = arr[min];
            arr[min] = t;
            index = min;
            left = index*2 + 1;
        }
    }
build pile

With the ability to adjust downwards above, we can adjust a complete binary tree with only one node that does not satisfy the heap characteristics into a heap, and so on, if an arbitrary complete binary tree can be found by finding the last one in its array For a non-leaf node , use this node to adjust downwards to make the tree under the node a heap, and then adjust it forward in the same way until it is adjusted to the root node in the entire binary tree . At this time, the heap is built

//建堆代码示例
public void buildHeap(int[] arr,int size){
    
    
        for(int i = (size-1-1)/2; i >= 0 ;i--){
    
    
            shiftDown(arr,size,arr[i]);
        }
    }

application (priority queue)

The elements stored in this collection of heaps can guarantee a characteristic, that is, its heap (the first element of the array) can always be guaranteed to be the maximum/minimum value in the collection, and we often have some requirements in life such as getting The priority of all things is because of this background combined with the characteristics of the heap to implement a special data structure - priority queue (priority queue)

features

: When dequeuing, the highest priority can always be guaranteed to be popped first

The official priorityQueue methodinsert image description here

Operating principle:

Enter the queue (take a large heap as an example):

  1. First insert the index position in the array according to the tail insertion method
  2. Compare it with its parent node ((index-1)/2 position and index/2-1 position), if it is less than, exit and enter the team successfully, otherwise exchange with the smallest node in the parent
  3. Go back to the second step and repeat until there is no parent node or the value is less than the parent node

insert image description here

//入队列的向上调整操作
public void shiftUp(int[] arr,int index){
    
    
        while(index > 0){
    
    
            int par = (index-1)/2;
            if(arr[par] > arr[index]){
    
    
                break;
            }
            int t = arr[par];
            arr[par] = arr[index];
            arr[index] = t;

            index = par;
        }
    }

Dequeuing: In order to prevent damage to the heap structure, when deleting, the top element of the heap is not directly deleted so that the cost of rebuilding the heap is too high, but the last element of the array is used to replace the top element of the heap, and then
readjusted heap

insert image description here

TopK questions:

Core: Create k small heaps , traverse the collection, compare the traversed elements with the top elements of the heap each time, if they are larger, exchange with the top of the heap, and adjust the heap once

public class topK{
    
    
    public static void main(String[] args) {
    
    
        System.out.println(topK(new int[]{
    
    5,3,4,8,7,6,1,2,9},3));
        System.out.println(topK(new int[]{
    
    },3));
        System.out.println(topK(new int[]{
    
    5,3,4,8,7,6,1,2,9},11));
        System.out.println(topK(new int[]{
    
    5,3,4,8,7,6,1,2,9},-1));
    }
    public static String topK(int[] nums,int k){
    
    
        if(k <= 0 || nums.length == 0){
    
    
            return "[]";
        }
        PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
    
    
            @Override
            public int compare(Integer o1, Integer o2) {
    
    
                return o1 - o2;
            }
        });
        for(int i = 0; i < nums.length; i++){
    
    
            if(i < k){
    
    
                pq.offer(nums[i]);
            }else{
    
    
                if(nums[i] > pq.peek()){
    
    
                    pq.poll();
                    pq.offer(nums[i]);
                }
            }
        }
        return pq.toString();
    }
}

Common comparison methods between objects

override equals() comparison

The comparison of objects in Java cannot use simple ">" "=" "<" comparison, because it is a reference type. If you use = to compare, it will compare whether the pointed addresses of the two references are the same, which is not the comparison we expected value size

Therefore, in order to compare the size of two objects, Java provides us with the equals() method. The equals() method is a method defined by Object, so all the objects we define inherit this method, and the native equals() of the Object class is also the same. Use = to compare

So when we compare the objects we define, we must override the equals() method and define the rules of comparison by ourselves.
insert image description here

class People{
    
    
    String name;
    int age;
    int high;
    int wight;

    public People(String name, int age, int high, int wight) {
    
    
        this.name = name;
        this.age = age;
        this.high = high;
        this.wight = wight;
    }

    @Override
    public boolean equals(Object o) {
    
    
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        People people = (People) o;
        return age == people.age;
    }
}
public class Test2 {
    
    
    public static void main(String[] args) {
    
    
        People people1 = new People("张三",18,175,80);
        People people2 = new People("李四",20,178,85);
        if(people1.equals(people2)){
    
    
            System.out.println("张三年纪大");
        }else{
    
    
            System.out.println("李四年纪大");
        }
    }
}

Implement Comparble interface comparison

For the convenience of object comparison, Java also provides a compatible interface, and the object implements the compareTo() method of this interface to realize the comparison function
insert image description here

//实现Comparable接口
class People implements Comparable{
    
    
    String name;
    int age;
    int high;
    int wight;

    public People(String name, int age, int high, int wight) {
    
    
        this.name = name;
        this.age = age;
        this.high = high;
        this.wight = wight;
    }

    @Override
    public int compareTo(Object o) {
    
    
        return this.age - ((People)o).age;
    }
}
public class Test2 {
    
    
    public static void main(String[] args) {
    
    
        People people1 = new People("张三",18,175,80);
        People people2 = new People("李四",20,178,85);
        if(people1.compareTo(people2) > 0){
    
    
            System.out.println("张三年纪大");
        }else{
    
    
            System.out.println("李四年纪大");
        }
    }
}

equals() stipulates that if the value of the object (this.val) is equal to the value of the incoming object (o.val), it returns true, otherwise it returns false The compareTo() of the compatible
interface stipulates that if the object If the value (this.val) is greater than the value (o.val) of the passed object, it will return 1, if it is equal to return 0, if it is less than it will return -1

comparator comparator

The comparator interface is similar to the compatible interface, which can implement the compare() method of the comparator interface to realize the comparison function between objects, and the compare() method is to pass in two parameters to compare two objects
insert image description here

equals, Comparble and comparator comparison

insert image description here

The comparison method used at the bottom of PriorityQueue in JDK

The bottom layer of PriorityQueue in the Java collection framework uses a heap structure, so the added elements must have comparison capabilities. PriorityQueue uses Comparble and Comparator two comparison methods
insert image description here

Comparble is the default comparison method inside PriorityQueue. If the user inserts an object, the class that creates the object must implement Comparble's ComparTo() method
insert image description here

Compare is a comparator that users can choose to add. If the user inserts an object, a Compare() method under the Comparator interface must be provided to the created PriorityQueue object. The above is a summary of the comparison knowledge points of
insert image description here
heap and Java objects. In-depth and synchronous supplements and modifications will be made to the content. It will be a great honor to help all bloggers, please correct me

Guess you like

Origin blog.csdn.net/m0_46233999/article/details/117814585