0

0

Java中自定义对象列表的快速排序实现与优化

霞舞

霞舞

发布时间:2025-11-10 17:25:00

|

617人浏览过

|

来源于php中文网

原创

Java中自定义对象列表的快速排序实现与优化

本教程详细介绍了如何在java中为自定义对象列表实现高效的快速排序算法。我们将重点探讨comparable接口中compareto方法的正确实现,以及快速排序核心的partition(分区)策略。通过分析常见错误并提供优化后的代码示例,帮助开发者理解并掌握快速排序在实际应用中的技巧和注意事项。

快速排序算法概述

快速排序(QuickSort)是一种高效的、基于比较的排序算法,其核心思想是“分而治之”。它通过一趟排序将待排序的数据分割成独立的两部分,其中一部分的所有数据都比另一部分的所有数据要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。快速排序的平均时间复杂度为O(n log n),在大多数实际应用中表现出色。

自定义对象与Comparable接口

在Java中对自定义对象进行排序时,需要让对象实现Comparable接口,并重写其compareTo方法。compareTo方法定义了对象之间进行比较的规则,这是排序算法能够正确工作的关键。

Location类结构

我们以一个Location类为例,该类包含邮政编码(zipCode)、城市(city)、经纬度等信息。我们将根据zipCode进行排序。

public class Location implements Comparable<Location> {

    private final String zipCode;
    private final String city;
    private final Double latitude;
    private final Double longitude;
    private final String state;

    public Location(String zipCode, Double latitude, Double longitude, String city, String state) {
        this.zipCode = zipCode;
        this.city = city;
        this.latitude = latitude;
        this.longitude = longitude;
        this.state = state;
    }

    public String getCity() {
        return this.city;
    }

    public String getZipCode() {
        return this.zipCode;
    }

    public Double getLatitude() {
        return latitude;
    }

    public Double getLongitude() {
        return longitude;
    }

    public String getState() {
        return state;
    }

    @Override
    public String toString() {
        return "Location{" +
               "zipCode='" + zipCode + '\'' +
               ", city='" + city + '\'' +
               '}';
    }

    // compareTo 方法将在下一节详细讨论和修正
    @Override
    public int compareTo(Location o) {
        // 修正后的 compareTo 实现
        // 将 zipCode 字符串转换为整数进行比较
        int thisZip = Integer.parseInt(this.zipCode);
        int otherZip = Integer.parseInt(o.getZipCode());

        return Integer.compare(thisZip, otherZip); // 推荐使用 Integer.compare
    }
}

compareTo方法的正确实现

Comparable接口的compareTo方法约定:

立即学习Java免费学习笔记(深入)”;

  • 如果当前对象(this)小于指定对象(o),返回负整数。
  • 如果当前对象等于指定对象,返回零。
  • 如果当前对象大于指定对象,返回正整数。

原始代码中的compareTo方法存在逻辑错误,它将“大于”返回-1,“小于”返回1,这与Comparable接口的约定相反,且未处理相等情况。

修正后的compareTo方法: 为了确保排序逻辑的正确性,我们将zipCode字符串转换为整数进行比较。最简洁和推荐的方式是使用Integer.compare()方法。

    @Override
    public int compareTo(Location o) {
        int thisZip = Integer.parseInt(this.zipCode);
        int otherZip = Integer.parseInt(o.getZipCode());

        // Integer.compare(x, y) 等价于 (x < y) ? -1 : ((x == y) ? 0 : 1)
        return Integer.compare(thisZip, otherZip);
    }

通过上述修正,Location对象现在可以根据其邮政编码进行正确的比较。

快速排序核心实现

快速排序主要由一个入口方法、一个递归排序方法和一个分区(partition)辅助方法组成。

1. 入口方法 quickSort

这个方法是快速排序的起点,它负责调用递归排序方法,并传入整个列表的初始范围。

ModelGate
ModelGate

一站式AI模型管理与调用工具

下载
public class QuickSortService { // 假设这是一个服务类来封装排序逻辑

    public void quickSort(List<Location> locations) {
        if (locations == null || locations.size() <= 1) {
            return; // 列表为空或只有一个元素,无需排序
        }
        quickSortRecursive(locations, 0, locations.size() - 1);
    }

    // ... 其他方法 ...
}

2. 递归排序方法 quickSortRecursive

这是快速排序的递归实现。它首先检查当前子数组的起始索引是否大于结束索引(递归基线条件),如果不是,则调用partition方法进行分区,然后对分区后的左右两个子数组进行递归排序。

    private void quickSortRecursive(List<Location> locations, int startIndex, int endIndex) {
        if (startIndex >= endIndex) { // 递归基线条件:子数组只有一个或没有元素
            return;
        }

        // 获取分区点(pivot的最终位置)
        int pivotIndex = partition(locations, startIndex, endIndex);

        // 对左侧子数组进行递归排序
        quickSortRecursive(locations, startIndex, pivotIndex - 1);
        // 对右侧子数组进行递归排序
        quickSortRecursive(locations, pivotIndex + 1, endIndex);
    }

3. 分区(partition)策略

partition方法是快速排序的核心。它的目标是:

  1. 选择一个基准元素(pivot)。
  2. 重新排列子数组中的元素,使得所有小于或等于基准的元素都放到基准的左边,所有大于基准的元素都放到基准的右边。
  3. 返回基准元素最终所在的位置。

这里我们采用“Lomuto partition scheme”的变种,选择子数组的第一个元素作为基准。

    private int partition(List<Location> locations, int startIndex, int endIndex) {
        Location pivot = locations.get(startIndex); // 选择第一个元素作为基准
        int smallerIndex = startIndex; // smallerIndex 跟踪小于基准的元素的右边界

        // 遍历从 startIndex + 1 到 endIndex 的所有元素
        for (int biggerIndex = startIndex + 1; biggerIndex <= endIndex; biggerIndex++) {
            // 如果当前元素小于或等于基准
            if (locations.get(biggerIndex).compareTo(pivot) <= 0) { // 使用修正后的 compareTo
                smallerIndex++; // 扩展小于基准元素的区域
                swapElements(locations, smallerIndex, biggerIndex); // 将当前元素交换到小于基准的区域
            }
        }
        // 最后,将基准元素(最初在 startIndex)与 smallerIndex 处的元素交换
        // 这样基准元素就到了它最终的正确位置
        swapElements(locations, startIndex, smallerIndex);
        return smallerIndex; // 返回基准元素的最终索引
    }

4. 元素交换(swapElements)辅助方法

这是一个简单的辅助方法,用于交换列表中两个指定索引位置的元素。

    private void swapElements(List<Location> input, int firstIndex, int secondIndex) {
        Location temp = input.get(firstIndex);
        input.set(firstIndex, input.get(secondIndex));
        input.set(secondIndex, temp);
    }

完整代码示例

将上述所有修正和实现整合,得到一个完整的、可用于对List<Location>进行快速排序的Java代码。

import java.util.List;
import java.util.Collections; // 虽然这里不用,但原问题中提到过

// Location.java 文件
class Location implements Comparable<Location> {

    private final String zipCode;
    private final String city;
    private final Double latitude;
    private final Double longitude;
    private final String state;

    public Location(String zipCode, Double latitude, Double longitude, String city, String state) {
        this.zipCode = zipCode;
        this.city = city;
        this.latitude = latitude;
        this.longitude = longitude;
        this.state = state;
    }

    public String getCity() {
        return this.city;
    }

    public String getZipCode() {
        return this.zipCode;
    }

    public Double getLatitude() {
        return latitude;
    }

    public Double getLongitude() {
        return longitude;
    }

    public String getState() {
        return state;
    }

    @Override
    public String toString() {
        return "Location{zipCode='" + zipCode + "', city='" + city + "'}";
    }

    @Override
    public int compareTo(Location o) {
        // 将 zipCode 字符串转换为整数进行比较
        int thisZip = Integer.parseInt(this.zipCode);
        int otherZip = Integer.parseInt(o.getZipCode());

        return Integer.compare(thisZip, otherZip);
    }
}

// QuickSortService.java 文件
public class QuickSortService {

    public void quickSort(List<Location> locations) {
        if (locations == null || locations.size() <= 1) {
            return;
        }
        quickSortRecursive(locations, 0, locations.size() - 1);
    }

    private void quickSortRecursive(List<Location> locations, int startIndex, int endIndex) {
        if (startIndex >= endIndex) {
            return;
        }

        int pivotIndex = partition(locations, startIndex, endIndex);

        quickSortRecursive(locations, startIndex, pivotIndex - 1);
        quickSortRecursive(locations, pivotIndex + 1, endIndex);
    }

    private int partition(List<Location> locations, int startIndex, int endIndex) {
        Location pivot = locations.get(startIndex); // 选择第一个元素作为基准
        int smallerIndex = startIndex; 

        for (int biggerIndex = startIndex + 1; biggerIndex <= endIndex; biggerIndex++) {
            if (locations.get(biggerIndex).compareTo(pivot) <= 0) { // 使用修正后的 compareTo
                smallerIndex++;
                swapElements(locations, smallerIndex, biggerIndex);
            }
        }
        swapElements(locations, startIndex, smallerIndex);
        return smallerIndex;
    }

    private void swapElements(List<Location> input, int firstIndex, int secondIndex) {
        Location temp = input.get(firstIndex);
        input.set(firstIndex, input.get(secondIndex));
        input.set(secondIndex, temp);
    }

    // 示例用法
    public static void main(String[] args) {
        List<Location> locations = new java.util.ArrayList<>();
        locations.add(new Location("90210", 34.0, -118.0, "Beverly Hills", "CA"));
        locations.add(new Location("10001", 40.0, -74.0, "New York", "NY"));
        locations.add(new Location("60601", 41.0, -87.0, "Chicago", "IL"));
        locations.add(new Location("90211", 34.1, -118.1, "Beverly Hills", "CA"));
        locations.add(new Location("00001", 10.0, -10.0, "Test City", "TS"));
        locations.add(new Location("60600", 41.0, -87.0, "Chicago", "IL"));

        System.out.println("Original List:");
        locations.forEach(System.out::println);

        QuickSortService sorter = new QuickSortService();
        sorter.quickSort(locations);

        System.out.println("\nSorted List:");
        locations.forEach(System.out::println);
    }
}

快速排序的注意事项与优化

  1. 基准元素(Pivot)的选择:

    • 选择第一个或最后一个元素: 最简单,但在已排序或逆序的数组中会导致最坏情况O(n^2)的性能。
    • 随机选择: 可以有效避免最坏情况,但引入了随机数生成的开销。
    • 三数取中(Median-of-three): 选择子数组的第一个、中间和最后一个元素的中位数作为基准。这通常是实践中较好的选择,因为它能更好地估计真实中位数,减少出现最坏情况的概率。
  2. 小规模子数组的处理: 当递归到非常小的子数组(例如,元素数量小于10-20个)时,快速排序的递归开销可能超过其效率优势。在这种情况下,切换到插入排序(Insertion Sort)等简单排序算法会更高效。

  3. 最坏情况分析: 如果每次选择的基准元素都使得分区非常不平衡(例如,总是选择最大或最小的元素),快速排序的时间复杂度会退化到O(n^2)。合理选择基准是避免这种情况的关键。

  4. 稳定性: 快速排序通常不是稳定排序算法。这意味着如果列表中存在相等的元素,它们的相对顺序在排序后可能发生改变。如果需要保持相等元素的相对顺序,则需要考虑其他稳定排序算法(如归并排序)。

总结

实现Java中自定义对象的快速排序,关键在于两个方面:

  1. 正确实现Comparable接口的compareTo方法:确保它严格遵循约定,返回负数、零或正数,以正确反映对象之间的比较关系。
  2. 正确实现partition(分区)策略:这是快速排序算法的核心,它负责将列表有效地划分为小于基准和大于基准的两个子集。

通过理解和应用这些原则,并结合适当的优化策略(如改进基准选择、处理小规模子数组),开发者可以构建出高效且健壮的快速排序实现。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
sort排序函数用法
sort排序函数用法

sort排序函数的用法:1、对列表进行排序,默认情况下,sort函数按升序排序,因此最终输出的结果是按从小到大的顺序排列的;2、对元组进行排序,默认情况下,sort函数按元素的大小进行排序,因此最终输出的结果是按从小到大的顺序排列的;3、对字典进行排序,由于字典是无序的,因此排序后的结果仍然是原来的字典,使用一个lambda表达式作为key参数的值,用于指定排序的依据。

409

2023.09.04

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

760

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

221

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1567

2023.10.24

字符串介绍
字符串介绍

字符串是一种数据类型,它可以是任何文本,包括字母、数字、符号等。字符串可以由不同的字符组成,例如空格、标点符号、数字等。在编程中,字符串通常用引号括起来,如单引号、双引号或反引号。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

651

2023.11.24

java读取文件转成字符串的方法
java读取文件转成字符串的方法

Java8引入了新的文件I/O API,使用java.nio.file.Files类读取文件内容更加方便。对于较旧版本的Java,可以使用java.io.FileReader和java.io.BufferedReader来读取文件。在这些方法中,你需要将文件路径替换为你的实际文件路径,并且可能需要处理可能的IOException异常。想了解更多java的相关内容,可以阅读本专题下面的文章。

1228

2024.03.22

php中定义字符串的方式
php中定义字符串的方式

php中定义字符串的方式:单引号;双引号;heredoc语法等等。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

1204

2024.04.29

go语言字符串相关教程
go语言字符串相关教程

本专题整合了go语言字符串相关教程,阅读专题下面的文章了解更多详细内容。

193

2025.07.29

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

26

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 4.4万人学习

C# 教程
C# 教程

共94课时 | 11.3万人学习

Java 教程
Java 教程

共578课时 | 81.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号