Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Assignment1 {
- //public static int[] steps = new int[7];
- public static int count = 0; //we only need to keep the current count
- public static void main(String[] args) {
- int[] array1={4,2,1,6,8,0,12};
- int[] array2={4,5,0,6,1,3,12};
- //print out a header row
- System.out.println("Key" +"\t"+ "Found" +"\t"+ "Steps");
- for(int i=0;i<7;i++){
- //key
- System.out.print(array2[i] + "\t");
- //found
- int foundAt = linearSearch(array1, array2[i]);
- if(foundAt < 0){ //if not found
- System.out.print("No" + "\t");
- }else{//if found
- System.out.print( foundAt + "\t");
- }
- //steps
- System.out.println(count);
- }
- }
- public static int linearSearch(int[] a,int key) {
- count = 0; //reset the count when we start a new search
- for(int i=0; i<a.length; i++) {
- count++; //increase the count in each loop
- if(key==a[i]) {
- return i;
- }
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement