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 700 in Array(100..1000) using RubyLabs: time { search(a, 700) } where a is an array
Create an array whose elements contain the integers from 100,000 through 300,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_even.rb, write a Ruby function all_even?(list) that takes an integer list as an argument and returns true if all the elements in the list are even numbers and false otherwise.
Example:
>> 4.even? => true >> 5.even? => false >> all_even?([1, 2, 8, 12, 99]) => false >> all_even?([4, 10, 14, 100]) => true
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.