Back to Search
[comp1110-86] - Fabian Muehlboeck
Back to Search
[comp1110-86]- Fabian Muehlboeck
Example 1. CLI driver for search procedures
[comp1110-1M] - Liam O'Connor
Example 1. CLI driver for search procedures
[comp1110-1M]- Liam O'Connor
To make manual testing easier, we'll make a suitable main function that reads a certain number of inputs
one number at a time using IO.readln() and then calls our search function.
The flexibility is nice, by but running this and manually entering a bunch of numbers every time can be a bit of a slog. You can therefore create a file, say "numbers.txt" (the file extension does not really matter), that contains those numbers:
You can of course create several different files with different lists of numbers.
To use those files, you can call your program in a special way. If you normally start the program by writing:
You can instead write:
The combination of a less-than sign < with a filename after it tells your terminal emulator to
read that file and use it as the standard input for the program, instead of prompting the user.
We use the same idea in Homework 1.
Example 2. Sortedness Checker
[comp1110-1K] - Liam O'Connor, Fabian Muehlboeck
Example 2. Sortedness Checker
[comp1110-1K]- Liam O'Connor, Fabian Muehlboeck
3. Searching Arbitrary Arrays
[comp1110-87] - Fabian Muehlboeck
3. Searching Arbitrary Arrays
[comp1110-87]- Fabian Muehlboeck
Binary Search is very efficient, but depends on the array being sorted. This may not be true of any array you might encounter. So, as a first attempt, you might want to use the sortedness checker from Example 2 to see if the array is sorted, and then depending on that either use binary search or the linear search procedure we saw in Example [comp1110-16].
The problem with the above approach is that when we are checking whether the array
is sorted, we have to go through every element of the array.
At that point, we might just check whether those elements are equal to needle
right away.
The general idea is more reasonable if there are several things that we want to search for. In that case, we only have to go through the array once, and if it happens to be sorted, we can then use binarySearch many times, efficiently finding each element.
But better yet, in that case, we might just want to sort the array to guarantee that we can do those later searches efficiently.