0 Replies - 183 Views - Last Post: 25 January 2013 - 02:51 PM Rate Topic: -----

#1 k3y  Icon User is offline

  • D.I.C Head

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

Java Assignment, please help [still stuck]

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