-2

I'm trying to implement a java code to test linear search on a sorted array and this is my code

public class ArrayTest {
public static void main(String [] args) {
    int []x= {12,8,6,23,6,5,17,20,9};
    int y  =linearSearch(x,23);
}
public static  int linearSearch(int []ar,int value) {
    int searchedIndex=-1;
    for(int i=0;i<ar.length;i++) {
        if (ar[i]==value) {
            searchedIndex=i;
            break;
        }
    }
    return searchedIndex ;
}

}

The problem is that this doesn't generate any output also no errors were generated. Can anyone explain the reason for this.

2 Answers2

1

In order to print something to the output,you must use System.out.println() function.The answer is returned to the variable y.Just print the variable to the console output.Moreover,the array is not sorted.But,that doesn't make any problem to it.

Sanjay Anbu
  • 55
  • 1
  • 4
0

Something like this:

import java.util.Arrays;

public class ArrayTest {

    public static void main(String[] args) {
        int[] x = {12, 8, 6, 23, 6, 5, 17, 20, 9};
//      Arrays.sort(x);
        int y = linearSearch(x, 23);
        System.out.println("" + y);
//      int z = Arrays.binarySearch(x, 23);
//      System.out.println("" + z);
    }

    public static int linearSearch(int[] ar, int value) {
        for (int i = 0; i < ar.length; i++) {
            if (ar[i] == value) {
                return i;
            }
        }
        return -1;
    }

}

Note the commented out lines are for if you actually wanted a sorted array instead of an unsorted array

Rick
  • 576
  • 3
  • 12