javascript - Javascript 中的搜索和冒泡排序数组

标签 javascript algorithm sorting

好吧,我在类里面遇到这个实验真的有问题。 问题是:

初始化:用 0 到 100 之间的整数值随机初始化一个大小为 200 的列表。 第 1 部分:搜索 您将实现一个函数,该函数在列表中搜索某个值的出现。它不应依赖于预先排序的列表。

搜索 部分规范注释 INPUT: list, value 一个初始化的列表 计算:

Loop over all elements in list.
    If current element equals value, store as index.
If value not found, ensure index is -1.

返回:索引 -1 如果找不到值

Prompt the user once for an element (an integer from 0 to 100) to search for.
Call your search function with the number to search for and the list.
Display whether the number was found, and if found, a location where it can be found within the list.

第 2 部分:排序 您将实现一个函数,该函数按 (0, 1, ...) 的升序对列表进行排序。不允许使用 JavaScript 的 sort() 方法。 有很多方法可以对列表进行排序,您可以在其中实现您认为合适的任何方法,前提是它按升序对列表进行排序。下面介绍冒泡排序,这是最直接的排序方法之一。

排序 部分规范注释 INPUT: list 一个初始化的列表 其他变量:交换 n 指示是否发生交换。 在列表中搜索多远。 计算:

Set n to size of list - 1.
Set swap to FALSE.
Loop over element 0 through element n in the list.
    If current element > next element
        Swap current element and next element.
        Set swap to TRUE.
If swap is TRUE, repeat from step 2. n -= 1.
If swap is FALSE, return the now sorted list.

Gradually sorts a list.

第 n 个项目已正确放置。 返回:列表

Call your sort function for your list. You are not permitted to call Javascript's sort() method.
Display the (sorted) list.

我不是要你做我的功课,但你能给我指出正确的方向吗?我想出了如何进行冒泡排序,但搜索部分是我遇到的主要问题。

最佳答案

function search(array, value)
{
    for (var i = 0; i < array.length; i++)
        if (array[i] === value)
            return i;
    return -1;
}

关于冒泡排序的实现,请阅读 this .

此外,您可以使用此解决方案:

function search(array, value)
{
    return array.indexOf(value);
}

关于javascript - Javascript 中的搜索和冒泡排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7930345/

相关文章:

c++ - 在 C++ 中,您将如何对字符串进行排序以使字谜彼此接近?

javascript - 检测文本框是否不包含某些单词

javascript - 如何很好地修改大量元素的属性?

algorithm - 通过倒数/Pearson's r 找到最优排序算法

python - 计算任意(非二叉)树的高度

javascript - 查找数组中的范围

c - 堆排序给出错误的输出

javascript - 检查主 UL 标签中是否存在控件?

javascript - 使用 Multer - 如何读取上传的文件 (text/.csv)

python - 最大小费计算器 - 天真的解决方案