文章配图:排序算法与奖品排序

页面预览

前言

在「猫猫大作战」的排行榜和合成结果展示中,排序是基础能力。ArkTS 的数组 sort() 方法用于对数组元素排序,但默认按字符串 ASCII 码排序——对数字排序需要传入比较函数。

本文以排行榜的排序实现为锚点,讲解数组排序的完整使用。

一、基础排序

// 默认排序(字符串顺序 — 对数字表现异常)
const nums = [1, 30, 4, 21, 100];
nums.sort(); // [1, 100, 21, 30, 4] ❌

// 正确:传入比较函数
nums.sort((a, b) => a - b);  // [1, 4, 21, 30, 100] ✅
nums.sort((a, b) => b - a);  // [100, 30, 21, 4, 1] ✅

二、对象数组排序

interface LeaderboardEntry {
  playerName: string;
  score: number;
  duration: number;
  gameDate: string;
}

// 按得分降序
const sorted = entries.sort((a, b) => b.score - a.score);

// 复合排序:得分降序,同分按用时升序
const sorted2 = entries.sort((a, b) => {
  if (a.score !== b.score) return b.score - a.score;
  return a.duration - b.duration;  // 同分用时短的靠前
});
排序方式 比较函数 场景
升序 a - b 数字从小到大
降序 b - a 排行榜得分
字符串升序 a.localeCompare(b) 玩家姓名
日期降序 new Date(b) - new Date(a) 最新记录

三、游戏中的排行榜排序

function sortLeaderboard(entries: LeaderboardEntry[]): LeaderboardEntry[] {
  return [...entries].sort((a, b) => {
    // 一级排序:得分降序
    if (a.score !== b.score) return b.score - a.score;
    // 二级排序:时长升序
    if (a.duration !== b.duration) return a.duration - b.duration;
    // 三级排序:日期升序(先完成的排名靠前)
    return new Date(a.gameDate).getTime() - new Date(b.gameDate).getTime();
  });
}

四、性能考虑

// 小数据量(< 1000)直接使用 sort(),时间复杂度 O(n log n)
// 大数据量(> 10000)考虑使用后端排序或索引

// 缓存排序结果
private sortedCache: LeaderboardEntry[] | null = null;
private lastSortKey: string = '';

getSortedLeaderboard(): LeaderboardEntry[] {
  const key = this.entries.map(e => e.score).join(',');
  if (key === this.lastSortKey && this.sortedCache) {
    return this.sortedCache;  // 数据未变,返回缓存
  }
  this.sortedCache = sortLeaderboard(this.entries);
  this.lastSortKey = key;
  return this.sortedCache;
}

五、常见错误

错误 表现 原因 修复
默认 sort 数字排序错误 字符串比较 传入比较函数
修改原数组 数据混乱 sort 会修改原数组 [...arr].sort()
浮点数比较 精度误差 a - b 对浮点数 比较差值绝对值

总结

ArkTS 的 sort() 方法配合比较函数,实现排行榜和历史记录的灵活排序。核心要点:数字排序必须传入比较函数、 复合排序链式条件、 不修改原数组 [...arr].sort()、 大数据量用后端排序

如果这篇文章对你有帮助,欢迎点赞👍、收藏⭐、关注🔔,你的支持是我持续创作的动力!


相关资源:

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐