在有序数组中查找插入索引

JavaScriptJavaScriptBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探索JavaScript编程的基础知识。通过一系列练习和挑战,我们将涵盖数据类型、变量、函数和控制流等主题。在本实验结束时,你将拥有坚实的JavaScript编程基础,并具备应对更高级概念的技能。准备好投身于令人兴奋的JavaScript世界吧!


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28402{{"`在有序数组中查找插入索引`"}} javascript/data_types -.-> lab-28402{{"`在有序数组中查找插入索引`"}} javascript/arith_ops -.-> lab-28402{{"`在有序数组中查找插入索引`"}} javascript/comp_ops -.-> lab-28402{{"`在有序数组中查找插入索引`"}} javascript/array_methods -.-> lab-28402{{"`在有序数组中查找插入索引`"}} end

如何在有序数组中找到插入索引

要找到将一个值插入有序数组的最低索引,请遵循以下步骤:

  1. 检查数组是否按降序排序。
  2. 使用 Array.prototype.findIndex() 方法找到应插入元素的合适索引。

以下是实现此功能的代码:

const sortedIndex = (arr, n) => {
  const isDescending = arr[0] > arr[arr.length - 1];
  const index = arr.findIndex((el) => (isDescending ? n >= el : n <= el));
  return index === -1 ? arr.length : index;
};

你可以通过传入有序数组和要插入的值来调用 sortedIndex 函数。以下是一些示例:

sortedIndex([5, 3, 2, 1], 4); // 输出: 1
sortedIndex([30, 50], 40); // 输出: 1

通过使用此函数,你可以轻松找到值在有序数组中的插入索引。

总结

恭喜你!你已经完成了“在有序数组中查找插入索引”实验。你可以在LabEx中练习更多实验来提升你的技能。

您可能感兴趣的其他 JavaScript 教程