Hannah Smith
Hannah Smith

Reputation: 11

Search and Bubble Sort Array in Javascript

Alright, so I'm really having trouble with this lab for my class. Here's the problem:

Initialization: Randomly initialize a list of size 200 with integer values between 0 and 100. Part 1: Search You are to implement a function which searches a list for an occurence of a value. It should not depend on the list being pre-sorted.

Search Section Specification Comments INPUT: list, value An initialized list COMPUTATION:

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

RETURN: index -1 if value not found

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.

Part 2: Sort You are to implement a function which sorts a list in ascending (0, 1, ...) order. You are not permitted to use JavaScript's sort() method. There are many ways to sort a list of which you may implement any method you see fit, provided it sorts a list in ascending order. Below describes Bubble Sort, one of the most straight-forward approaches to sorting.

Sort Section Specification Comments INPUT: list An initialized list OTHER VARIABLES: swap n Indicates if swap occurred. How far to search in the list. COMPUTATION:

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.

nth item is correctly placed. RETURN: list

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

I'm not asking you to do my homework but can you please just point me in the right direction? I figured out how to do the bubble sort but the search part is what I'm mostly having problems with.

Upvotes: 1

Views: 1558

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76591

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

For Bubble Sort implementation please read this.

Also, you can use this solution:

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

Upvotes: 2

Related Questions