Looking inside an Array

Linear search is simplest searching algorithm to find an element in an array. This example has an array with  6 elements. A key is value that we are looking for inside of an array, and we are looking for value 4. Another integer variable index is used for storing index value of element that has matching value as the key value. We initialize index with arr.length, which it return the size of the array.

Out search engine build using for loop. This engine will check all the elements in the array one by one. The if statement inside the loop is where it checks whether value of arr at current location indicated by variable i is same as value of key. If the values are equal we change the index value to value of i.

Third part is displaying results. If the value of index not equal to arr.length, that means something has happen inside the loop statement. This something can happen only and only if key is found inside the array. So this if statement actually checks whether the key is found or not. Thus, if the key is found it display key is found at which index position or else key not found message is displayed.

The Java Code:


public class LinearSearch {

   public static void main(String[] args) {
     int arr[] = {2,3,1,4,6,8};   // the array that we want to look into
     int key = 4;                        // number to search for
     int index = arr.length;      // variable to keep index number
    
     // the search engine
     for(int i=0;i<arr.length;i++){
        if(arr[i] == key){
           index = i;
        }
     }
    
     //display result
     if(index != arr.length){
        System.out.println("Number " + key + " is found at index " + index);
     }else{
        System.out.println("Number " + key + " is not found");
     }
   }
}

Output:

case 1: if key is found

In this case the value given to this program is 4, which suppose to be found by the program inside the array. The index value is 3 because all array starts from index value 0.

Number 4 is found at index 3

case 2: if key not found

The second case happens if the key value given is not in the array. The value of index will  remain unchanged for this case.

Number 7 is not found

Next, we will look into improved version of search engine. 

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net