Answers for "linear search java"

2

Linear search in java

public class LinearSearchExample
{
   // here function returns index of element x in arrLinear
   static int searchNumber(int[] arrLinear, int key)
   {
      int num = arrLinear.length;
      for(int a = 0; a < num; a++)
      {
         // here we are returning the index of the element if found
         if(arrLinear[a] == key)
            return a;
      }
      // here we are returning -1 if element is not found
      return -1;
   }
   public static void main(String[] args)
   {
      int[] arrLinear = {15, 25, 35, 55, 75, 95};
      int key = 55;
      int output = searchNumber(arrLinear, key);
      if(output == -1)
      {
         System.out.println("Sorry!!Element is not present");
      }
      else
      {
         System.out.println("Element is present at index " + output);
      }
   }
}
Posted by: Guest on December-30-2020
2

how to do a linear searc in java

public static int linear(int[] arr, int keyValue)
{
  int pos = -1; 

    for (int i = 0; i < arr.length; i++)
    {
        if (arr[i] == keyValue)
        {
            pos = i;
            break;
        }
	}
	return pos;
}
Posted by: Guest on April-15-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language