Page 1 of 1

## 0 Replies - 363 Views - Last Post: 25 January 2013 - 02:51 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=309323&amp;s=9064b3986abb94c28cf11f8398844850&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 k3y

Reputation: 36
• Posts: 205
• Joined: 25-February 12

Posted 25 January 2013 - 02:51 PM

Howdy folks;
I have been assigned a problem by my professor, and I think I have completed all of the points specified, however; he still says that I have not completed the assignment. I would deeply appreciate any help that anyone can provide. I have posted both my code, and the assignment below.
ASSIGNMENT

Quote

In this program you will prove that on average, binary search works better than linear search.
1. Create a sorted list of 20 numbers.
2. Search for each element using linear search and print out the number of iterations before the item is found.
3. Now use binary search and print the same information.
4. Print the average number of iterations for each search.
5. You should be able to show that binary search does not always perform better than linear search but does perform better on average.
You will find the Binary Search and the Sequential search in the Unit 10 Coding folder.

CODE:
import java.util.*;
public class Assignment1
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
//point 1
int[] numberList = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
16, 17, 18, 19, 20
};

for(int x = 0; x < numberList.length; x++)
{
System.out.println("sequential search: ");
System.out.println(seqSearch(numberList, numberList[x]));
System.out.println();
System.out.println("binary search: ");
System.out.println(binSearch(numberList, numberList[x]));
}
}
public static int seqSearch(int[] array, int searchItem)
{
int iterations = 0;
for(int x = 0; x < array.length; x++)
{
iterations++;
if(array[x] == searchItem)
{
System.out.println("number of iterations(seq): " + iterations);
return x;
}
}
return -1;
}
public static int binSearch(int[] array, int searchItem)
{
int iterations = 0;
int start = 0;
int mid;
int end = array.length-1;
while (start <= end)
{
iterations++;
mid = ((start + end) / 2);
if (searchItem == array[mid])
{
System.out.println("number of iterations(bin): " + iterations);
return mid;
}
else if (searchItem < array[mid])
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
return -1;
}
}

Is This A Good Question/Topic? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }