Advertisement
Guest User

Assignment 1

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