Answers for "java sort and inheritence"

0

java sort and inheritence

import java.util.*;

class Arrange

{

 void sort(int a[])

 {

   int i,j,t=0;

   for(i=0;i<a.length;i++)

    for(j=0;j<a.length-i-1;j++)

    {

      if(a[j]>a[j+1])

      {

        t=a[j];

        a[j]=a[j+1];

        a[j+1]=t;

       }

     }

  }  

}

// Class for searching a key in a sorted list of elements(inherits Arrange class)

class Search extends Arrange

{

 Search(int x[],int key)

 {

  sort(x);

  System.out.println("Sorted list of elements is=");

  for(int i=0;i<x.length;i++)

   System.out.println(" "+x[i]);

  int low=0,high=x.length-1,mid;

  while(low<=high)

  {

    mid=(low+high)/2;

    if(x[mid]==key)

    {

    System.out.println("KEY FOUND");

     break;

    }

    else

     if(key<x[mid])

       high=mid-1;

     else

            low=mid+1;

  }

  if(low>high)

    System.out.println("KEY NOT FOUND");

  }

}

// MAIN CLASS

class Enter

{

 public static void main(String args[])

 {

   Scanner s=new Scanner(System.in);

   System.out.println("Enter the number of elements you want to enter");

   int size=s.nextInt();

   System.out.println("Enter the Elements");

   int x[]=new int[size];

   for(int i=0;i<x.length;i++)

     x[i]=s.nextInt();

   System.out.println("Enter the key element you want to find");

     int key=s.nextInt();

   Search n=new Search(x,key);

 }

}
Posted by: Guest on September-20-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language