Place these files in a lab4 folder. Before leaving lab, zip up the lab4 folder and hand in the zip file.
def search(list, key) len = list.length index = 0 while index < len do if list[index] == key then return index end index = index + 1 end return nil endtiming linear search for 300 in Array(200...400)
Create an array whose elements contain the integers from 100,000 through 200,000, inclusive and set the variable big_list to contain that array.
Use the Rubylabs time { expr } construct to time how long it takes the search function above to find each of the following in big_list:
How long does each take?
If you repeat the same searches, does it take exactly the same amount of time? Why do you think this is?
How would you describe the relationship between the position of the item you are searching for in the list and how long it takes to find that item? (Is the search time independent of the position, or is there some mathematical relationship between the two quantities?)
Write your answers in a text file called timings.txt.
In all_odd.rb, write a Ruby function all_odd?(list) that takes an integer list as an argument and returns true if all the elements in the list are odd numbers and false otherwise.
Example:
>> 3.odd? => true >> 4.odd? => false >> all_odd?([1, 3, 7, 11, 99]) => true >> all_odd?([1, 4, 7, 14, 99]) => false
In bubble_sort.rb, write a Ruby function bsort!(list) that will arrange the elements of the array list in descending order. (Note, the "!" is part of the name of the function. There is a convention among Ruby programmers to add exclamation points to the names of functions that modify their arguments or the object to which they belong.)
Use the following algorithm:
Example:
>> a = [-2, 5, 0, -4, 8, 0, 9] => [-2, 5, 0, -4, 8, 0, 9] >> bsort!(a) => [9, 8, 5, 0, 0, -2, -4] >> a => [9, 8, 5, 0, 0, -2, -4]
Challenge:
The above algorithm repeats step II.A.1 more times than is necessary. Modify your code to restrict the range of \(j\), so that unnecessary executions of II.A.1 are avoided.
In the algorithm given above, the number of times the loop is repeated is independent of the contents of list. Modify the algorithm so that it detects when list has become sorted and returns nil immediately.