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

Search and Bubble Sort Array in Javascript

本文关键字:冒泡排序 数组 搜索 Javascript      更新时间:2023-09-26

好吧,所以我在课堂上的这个实验室真的很麻烦。问题是:

初始化:随机初始化一个大小为200、整数值在0到100之间的列表。第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((方法。有很多方法可以对列表进行排序,您可以实现任何您认为合适的方法,只要它按升序排序即可。下面介绍了Bubble 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;
}

对于Bubble Sort的实现,请阅读本文。

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

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