I was reading about arrays and I programmed the first code below . The teacher did program the second code for searching in an array for a specific number. What is the difference in ordo notation between the two following codes in java . Which code performs better and what its big O notation.
My code
public static void main(String[] args)
{
int[] data = { 100, 110, 120, 130, 140, 150 };
int index = binarySearch(data, 120);
System.out.println(index);
}
private static int binarySearch(int[] data, int i)
{
if (data.length == 0)
{
return -1;
}
for (int k = 0; k < data.length; k++)
{
if (data[k] == i)
{
return k;
}
}
return -1;
}
Teacher's code
public static void main(String[] args)
{
int[] data = { 100, 110, 120, 130, 140, 150 };
int index = binarySearch(data, 120);
System.out.println(index);
}
static int binarySearch(int[] keys, int v)
{
int position;
int begin = 0, end = keys.length - 1;
while (begin <= end)
{
position = (begin + end) / 2;
if (keys[position] == v)
{
return position;
}
else if (keys[position] < v)
{
begin = position + 1;
}
else
{
end = position - 1;
}
}
return -1;
}