2011-10-28 45 views
1

好的,所以我真的对这个实验室遇到了麻烦。 这里的问题:在Javascript中搜索和排序排列数组

初始化:随机初始化0和100之间 第1部分尺寸200的整数值列表:搜索 你是为了实现其搜索列表中的值的occurence功能。它不应该依赖于预先排序的列表。

搜索 部分说明评论 输入:列表,值的初始化列表 计算:

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

RETURN:索引;如果值没有找到

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,这是最直接的排序方法之一。

排序 部分说明评论 输入:列表中的初始化列表 其他变量:交换 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项正确放置。 RETURN:列表

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

我不是让你做我的作业,但可以请你只点我在正确的方向?我想出了如何进行冒泡排序,但搜索部分是我最常遇到的问题。

+1

嗨汉娜,欢迎SO。你能发布你写过的JavaScript代码 - 至少是它的相关部分... –

+0

这是一部家庭作业吗? :) –

+0

你在哪个步骤面临问题? – r15habh

回答

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

对于Bubble Sort执行请阅读this

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

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

谢谢lajos –

+0

很高兴。你试过这个吗? –