Advertisement
Guest User

Assignment1

a guest
Feb 17th, 2020
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1.  
  2. public class Assignment1 {
  3.     //public static int[] steps = new int[7];
  4.     public static int count = 0; //we only need to keep the current count
  5.    
  6.     public static void main(String[] args) {
  7.         int[] array1={4,2,1,6,8,0,12};
  8.         int[] array2={4,5,0,6,1,3,12};
  9.  
  10.         //print out a header row
  11.         System.out.println("Key" +"\t"+ "Found" +"\t"+ "Steps");
  12.  
  13.         for(int i=0;i<7;i++){
  14.             //key
  15.             System.out.print(array2[i] + "\t");
  16.            
  17.             //found
  18.             int foundAt = linearSearch(array1, array2[i]);
  19.             if(foundAt < 0){ //if not found
  20.                 System.out.print("No" + "\t");
  21.             }else{//if found
  22.                 System.out.print( foundAt + "\t");
  23.             }
  24.            
  25.             //steps
  26.             System.out.println(count);
  27.         }
  28.     }
  29.  
  30.     public static int linearSearch(int[] a,int key) {
  31.         count = 0; //reset the count when we start a new search
  32.         for(int i=0; i<a.length; i++) {
  33.             count++; //increase the count in each loop
  34.             if(key==a[i]) {
  35.                 return i;
  36.             }
  37.         }
  38.         return -1;
  39.     }
  40.    
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement