算法与数据结构全阶班-左程云版(二)基础阶段之4.堆和比较器(下)

简介: 本文主要介绍了堆和比较器:堆包括大根堆和小根堆;比较器的实质就是重载比较运算符,可以用于普通方式的排序和自定义的排序。

2.比较器

比较器:

1)比较器的实质就是重载比较运算符

2)比较器可以很好的应用在特殊标准的排序上;

3)比较器可以很好的应用在根据特殊标准排序的结构上;

4)写代码变得异常容易,还用于范型编程。

先实现应用在特殊标准的排序,如下:

package heap04;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeMap;
/**
 * @author Corley
 * @date 2021/10/13 17:22
 * @description LeetCodeAlgorithmZuo-heap04
 */
public class CustomComparator {
    static class Student {
        private final String name;
        private final int id;
        private final int age;
        public Student(String name, int id, int age) {
            this.name = name;
            this.id = id;
            this.age = age;
        }
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", id=" + id +
                    ", age=" + age +
                    '}';
        }
    }
    /*
    * id升序比较器
    * */
    static class IdAscendingComparator implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.id - o2.id;
        }
    }
    /*
    * 年龄降序比较器
    * */
    static class AgeDescendingComparator implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o2.age - o1.age;
        }
    }
    /*
    * 复杂比较器,年龄降序、id升序
    * */
    static class AgeDescendingIdAscedingComparator implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.age != o2.age ? o2.age - o1.age : o1.id - o2.id;
        }
    }
    public static void main(String[] args) {
        Student student1 = new Student("A", 3, 40);
        Student student2 = new Student("B", 2, 21);
        Student student3 = new Student("C", 4, 12);
        Student student4 = new Student("D", 5, 62);
        Student student5 = new Student("E", 3, 42);
        Student[] studentArray = new Student[] {student1, student2, student3, student4, student5};
        Arrays.sort(studentArray, new IdAscendingComparator());
        System.out.println(Arrays.toString(studentArray));
        System.out.println("-------------------------------------");
        ArrayList<Student> studentList = new ArrayList<>();
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);
        studentList.add(student4);
        studentList.add(student5);
        studentList.sort(new AgeDescendingComparator());
        System.out.println(studentList);
        System.out.println("-------------------------------------");
        TreeMap<Student, String> studentMap = new TreeMap<>(new AgeDescendingIdAscedingComparator());
        studentMap.put(student1, "我是学生1,我的名字叫A");
        studentMap.put(student2, "我是学生2,我的名字叫B");
        studentMap.put(student3, "我是学生3,我的名字叫C");
        studentMap.put(student4, "我是学生4,我的名字叫D");
        studentMap.put(student5, "我是学生5,我的名字叫E");
        System.out.println(studentMap.keySet());
    }
}

输出:

[Student{name='B', id=2, age=21}, Student{name='A', id=3, age=40}, Student{name='E', id=3, age=42}, Student{name='C', id=4, age=12}, Student{name='D', id=5, age=62}]
-------------------------------------
[Student{name='D', id=5, age=62}, Student{name='E', id=3, age=42}, Student{name='A', id=3, age=40}, Student{name='B', id=2, age=21}, Student{name='C', id=4, age=12}]
-------------------------------------
[Student{name='D', id=5, age=62}, Student{name='E', id=3, age=42}, Student{name='A', id=3, age=40}, Student{name='B', id=2, age=21}, Student{name='C', id=4, age=12}]

再实现应用在根据特殊标准排序的结构,如下:

package heap04;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
 * @author Corley
 * @date 2021/10/13 14:56
 * @description LeetCodeAlgorithmZuo-heap04
 */
public class HeapUse {
    /*
     * 整型比较器
     * */
    static class IntegerComparator implements Comparator<Integer> {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    }
    public static void main(String[] args) {
        // PriorityQueue<Integer> heap = new PriorityQueue<>();
        // 大根堆
        PriorityQueue<Integer> heap = new PriorityQueue<>(new IntegerComparator());
        heap.add(5);
        heap.add(7);
        heap.add(3);
        heap.add(0);
        heap.add(5);
        heap.add(2);
        while (!heap.isEmpty()) {
            System.out.println(heap.poll());
        }
    }
}

可以看到,用PriorityQueue实现了大根堆。

语言提供的堆结构vs手写的堆结构:

取决于有没有动态改信息的需求;

语言提供的堆结构,如果你动态改数据,不保证依然有序

手写堆结构,因为增加了对象的位置表,所以能够满足动态改信息的需求。

思路如下:

2345_image_file_copy_146.jpg

实现如下:

package heap04;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;
/**
 * @author Corley
 * @date 2021/10/13 19:24
 * @description LeetCodeAlgorithmZuo-heap04
 */
public class CustomHeap {
    static class SelfHeap<T> {
        private final ArrayList<T> heap;                // 小根堆
        private final HashMap<T, Integer> indexMap;
        private int heapSize;
        private final Comparator<? super T> comparator;
        public SelfHeap(Comparator<? super T> comparator) {
            heap = new ArrayList<>();
            indexMap = new HashMap<>();
            heapSize = 0;
            this.comparator = comparator;
        }
        public boolean isEmpty() {
            return heapSize == 0;
        }
        public int size() {
            return heapSize;
        }
        public boolean contains(T key) {
            return indexMap.containsKey(key);
        }
        public void push(T value) {
            heap.add(value);
            indexMap.put(value, heapSize);
            heapInsert(heapSize++);
        }
        public T pop() {
            T ans = heap.get(0);
            int end = heapSize - 1;
            swap(0, end);
            heap.remove(end);
            indexMap.remove(ans);
            heapify(0, --heapSize);
            return ans;
        }
        public void resign(T value) {
            int valueIndex = indexMap.get(value);
            heapInsert(valueIndex);
            heapify(valueIndex, heapSize);
        }
        private void heapInsert(int index) {
            while (comparator.compare(heap.get(index), heap.get((index - 1) / 2)) < 0) {
                swap(index, (index - 1) / 2);
                index = (index - 1) / 2;
            }
        }
        private void heapify(int index, int heapSize) {
            int left = index * 2 + 1;
            while (left < heapSize) {
                int smallest = left + 1 < heapSize && (comparator.compare(heap.get(left + 1), heap.get(left)) < 0) ?
                        left + 1 : left;
                smallest = comparator.compare(heap.get(smallest), heap.get(index)) < 0 ? smallest : index;
                if (smallest == index) {
                    break;
                }
                swap(smallest, index);
                index = smallest;
                left = index * 2 + 1;
            }
        }
        private void swap(int i, int j) {
            T t1 = heap.get(i);
            T t2 = heap.get(j);
            heap.set(i, t2);
            heap.set(j, t1);
            indexMap.put(t1, j);
            indexMap.put(t2, i);
        }
    }
    public static class Student {
        public int classNo;
        public int age;
        public int id;
        public Student(int c, int a, int i) {
            classNo = c;
            age = a;
            id = i;
        }
    }
    public static class StudentComparator implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.age - o2.age;
        }
    }
    public static void main(String[] args) {
        Student s1 = new Student(2, 50, 11111);
        Student s2 = new Student(1, 60, 22222);
        Student s3 = new Student(6, 10, 33333);
        Student s4 = new Student(3, 20, 44444);
        Student s5 = new Student(7, 72, 55555);
        Student s6 = new Student(1, 14, 66666);
        SelfHeap<Student> myHeap = new SelfHeap<>(new StudentComparator());
        myHeap.push(s1);
        myHeap.push(s2);
        myHeap.push(s3);
        myHeap.push(s4);
        myHeap.push(s5);
        myHeap.push(s6);
        while (!myHeap.isEmpty()) {
            Student cur = myHeap.pop();
            System.out.println(cur.classNo + "," + cur.age + "," + cur.id);
        }
    }
}

之所以这种方式可以实现修改其中的元素后能重新排序,一个重要的原因是因为存入堆中的其实只是元素的引用,在修改元素的属性之后,引用对应的堆区对象的属性就会发生改变,所以相当于堆中的某个元素的属性发生变化,此时如果以这个属性为排序依据,则需要调用heapInsert和heapify方法对堆进行调整,以满足大根堆或小根堆的条件。

在实际使用中,选择堆时,如果只是单纯向堆中加入或取元素,则可以直接使用系统提供的堆;

如果需要对堆中的元素进行修改,则需要自己实现堆和对应的比较器。

总结

堆是在完全二叉树的基础上实现的,分为大根堆和小根堆,堆排序实现了O(N*LogN)的时间复杂度。比较器可以很好的应用在特殊标准的排序和根据特殊标准排序的结构上。

相关文章
|
2月前
|
存储 监控 安全
企业上网监控系统中红黑树数据结构的 Python 算法实现与应用研究
企业上网监控系统需高效处理海量数据,传统数据结构存在性能瓶颈。红黑树通过自平衡机制,确保查找、插入、删除操作的时间复杂度稳定在 O(log n),适用于网络记录存储、设备信息维护及安全事件排序等场景。本文分析红黑树的理论基础、应用场景及 Python 实现,并探讨其在企业监控系统中的实践价值,提升系统性能与稳定性。
66 1
|
2月前
|
存储 监控 算法
基于跳表数据结构的企业局域网监控异常连接实时检测 C++ 算法研究
跳表(Skip List)是一种基于概率的数据结构,适用于企业局域网监控中海量连接记录的高效处理。其通过多层索引机制实现快速查找、插入和删除操作,时间复杂度为 $O(\log n)$,优于链表和平衡树。跳表在异常连接识别、黑名单管理和历史记录溯源等场景中表现出色,具备实现简单、支持范围查询等优势,是企业网络监控中动态数据管理的理想选择。
77 0
|
6月前
|
存储 算法 Java
算法系列之数据结构-二叉树
树是一种重要的非线性数据结构,广泛应用于各种算法和应用中。本文介绍了树的基本概念、常见类型(如二叉树、满二叉树、完全二叉树、平衡二叉树、B树等)及其在Java中的实现。通过递归方法实现了二叉树的前序、中序、后序和层次遍历,并展示了具体的代码示例和运行结果。掌握树结构有助于提高编程能力,优化算法设计。
185 10
 算法系列之数据结构-二叉树
|
6月前
|
算法 Java
算法系列之数据结构-Huffman树
Huffman树(哈夫曼树)又称最优二叉树,是一种带权路径长度最短的二叉树,常用于信息传输、数据压缩等方面。它的构造基于字符出现的频率,通过将频率较低的字符组合在一起,最终形成一棵树。在Huffman树中,每个叶节点代表一个字符,而每个字符的编码则是从根节点到叶节点的路径所对应的二进制序列。
155 3
 算法系列之数据结构-Huffman树
|
6月前
|
算法 Java
算法系列之数据结构-二叉搜索树
二叉查找树(Binary Search Tree,简称BST)是一种常用的数据结构,它能够高效地进行查找、插入和删除操作。二叉查找树的特点是,对于树中的每个节点,其左子树中的所有节点都小于该节点,而右子树中的所有节点都大于该节点。
187 22
|
3天前
|
传感器 机器学习/深度学习 算法
【使用 DSP 滤波器加速速度和位移】使用信号处理算法过滤加速度数据并将其转换为速度和位移研究(Matlab代码实现)
【使用 DSP 滤波器加速速度和位移】使用信号处理算法过滤加速度数据并将其转换为速度和位移研究(Matlab代码实现)
|
5天前
|
机器学习/深度学习 算法 调度
基于NSGA-III算法求解微电网多目标优化调度研究(Matlab代码实现)
基于NSGA-III算法求解微电网多目标优化调度研究(Matlab代码实现)
|
4天前
|
传感器 算法 数据挖掘
基于协方差交叉(CI)的多传感器融合算法matlab仿真,对比单传感器和SCC融合
基于协方差交叉(CI)的多传感器融合算法,通过MATLAB仿真对比单传感器、SCC与CI融合在位置/速度估计误差(RMSE)及等概率椭圆上的性能。采用MATLAB2022A实现,结果表明CI融合在未知相关性下仍具鲁棒性,有效降低估计误差。
|
5天前
|
负载均衡 算法 调度
基于遗传算法的新的异构分布式系统任务调度算法研究(Matlab代码实现)
基于遗传算法的新的异构分布式系统任务调度算法研究(Matlab代码实现)
68 11
|
5天前
|
机器学习/深度学习 传感器 算法
基于全局路径的无人地面车辆的横向避让路径规划研究[蚂蚁算法求解](Matlab代码实现)
基于全局路径的无人地面车辆的横向避让路径规划研究[蚂蚁算法求解](Matlab代码实现)

热门文章

最新文章