Binary Search

In this section, we'll talk about one of the most well-known algorithms, known as the Binary Search Algorithm. 

Binary Search

So what is a searching algorithm anyway? A search algorithm is an algorithm designed to make searching for an element as efficient as possible. 

Idea:

Method 1:

We can simply do an exhaustive search. Suppose our int array has elements n elements. We can use a for loop to traverse the entire array to find when 

Example: This method will add whatever element is in the parenthesis into the queue. For example, if we have an                             integer queue with elements {1,2,3,4,5}, and we write q.add(6), the new value of q is 

{1,2,3,4,5,6}

Method 2 (Binary Search):

q.remove()

This method will remove the first element in the queue. Take the example where we had 

q. = {1,2,3,4,5}. Then after we take q.remove(), we will get q={2,3,4,5}

Method 3:

q.element()

This method will return the first element in the queue without adding or removing anything. For example, if we have q={1,2,3,4,5,6}, and we let int x = q.element(), then x=1.

More Methods:

Iteration:  As with any data structure, iteration is always important. How do we iterate through a queue?

Example 1:

                                        {  

                                               Queue<Integer> q = new LinkedList<Integer>();

                                               q.add(1);

                                               q.add(2);

                                               q.add(3);

                                               q.add(4);

                                               for(Integer item: q){

                                                     System.out.println(item);

                                               }

                                          }

When we want to iterate over a queue, we can use an enhanced for loop, or "for-each" loop to do so. This will allow us to access all of the elements in the queue with ease.

Exercise(s):

1. Make an integer Queue, and copy the contents of the queue to another queue using loops.