Thursday 7 June 2012

import java.io.*;
import java.util.*;
class ArraysDemo
{
public static void main(String args[])throws IOException
{ // to accept data from key board 
BufferedReader br=new BufferedReader(new  InputStreamReader(System.in));                        System.out.print("How many elements you want : "); 
 int n=Integer.parseInt(br.readLine( ));     // create int type array
int arr[]=new int[n];
// store elements into array
for(int i=0;i<n;i++)

                              System.out.print("Enter element : ");        arr[i]=Integer.parseInt(br.readLine( ));
} 
// display the elements
System.out.print("Your Array is : "+”\t”);
display(arr); 
// sort the elements in to ascending order
Arrays.sort(arr);
// display the sorted elements
System.out.print("Sorted array is : "+”\t”);
display(arr);
// searches for an element in an array
System.out.println("Enter element to Search : ");
int x=Integer.parseInt(br.readLine( ));
int pos=Arrays.binarySearch(arr,x);
if(pos<0)
System.out.println("Element not Found");
else                        System.out.println("it position is :"+(pos+1));
}
static void display(int arr[])
{
 for(int i:arr)
 System.out.println(i);
            }
}

D:\psr\Core java>javac ArraysDemo.java
D:\psr\Core java>java ArraysDemo
How many elements you want :
4
Enter element : 7
Enter element : 9
Enter element : 3
Enter element : 6
Your Array is : 7       9          3          6
Sorted array is : 3      6          7          9
Enter element to Search :
9
it position is :4

0 comments:

Post a Comment

Blogroll

Blogger templates

About