Saturday, March 14, 2015

search an element inside it java pgm



sort an array and search an element inside it

import java.util.Arrays;
public class MainClass
{
   public static void main(String args[]) throws Exception
{
      int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 2);
      System.out.println("Found 2 @ " + index);
   }
   private static void printArray(String message, int array[])
 {
      System.out.println(message
      + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++)
{

Result:

Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Found 2 @
 5

No comments:

Post a Comment