// How to sort an array and search an element inside it?
import java.io.*;
class ArraySortSearch
{
public static void main(String[] args)throws IOException
{
int i,j;
System.out.println("** Welcome to Arrays **");
System.out.println("Enter number of elements you want to insert into array: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
//declaring arrays
int myarr[]=new int[n];
//insert elements into array
System.out.println("Enter '+n' Elements: ");
for (i=0;i<n;i++)
{
myarr[i]=Integer.parseInt(br.readLine());
}
//displaying elements of an array
System.out.println("Entered elements are: ");
for (i=0;i<n ;i++ )
{
System.out.println(myarr[i]);
}
// sorting technique (bubble sort)
System.out.println("**** SORTING ****");
for (i=0;i<(n-1);i++ )
{
for(j=0;j< n-i-1;j++)
{
if(myarr[j]>myarr[j+1])
{
int temp=myarr[j];
myarr[j]=myarr[j+1];
myarr[j+1]=temp;
}
}
}
System.out.println("Sorted elements are: ");
for (i=0;i<n ;i++ )
{
System.out.println(myarr[i]);
}
// Sorting Ends
System.out.println("**** SEARCHING ****");
//Searching Starts
System.out.println("Enter element to be searched: ");
int s = Integer.parseInt(br.readLine());
for (i=0;i<n ;i++ )
{
if(s==myarr[i])
System.out.println("Element found at " +i+ " position");
}
}
}
import java.io.*;
class ArraySortSearch
{
public static void main(String[] args)throws IOException
{
int i,j;
System.out.println("** Welcome to Arrays **");
System.out.println("Enter number of elements you want to insert into array: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
//declaring arrays
int myarr[]=new int[n];
//insert elements into array
System.out.println("Enter '+n' Elements: ");
for (i=0;i<n;i++)
{
myarr[i]=Integer.parseInt(br.readLine());
}
//displaying elements of an array
System.out.println("Entered elements are: ");
for (i=0;i<n ;i++ )
{
System.out.println(myarr[i]);
}
// sorting technique (bubble sort)
System.out.println("**** SORTING ****");
for (i=0;i<(n-1);i++ )
{
for(j=0;j< n-i-1;j++)
{
if(myarr[j]>myarr[j+1])
{
int temp=myarr[j];
myarr[j]=myarr[j+1];
myarr[j+1]=temp;
}
}
}
System.out.println("Sorted elements are: ");
for (i=0;i<n ;i++ )
{
System.out.println(myarr[i]);
}
// Sorting Ends
System.out.println("**** SEARCHING ****");
//Searching Starts
System.out.println("Enter element to be searched: ");
int s = Integer.parseInt(br.readLine());
for (i=0;i<n ;i++ )
{
if(s==myarr[i])
System.out.println("Element found at " +i+ " position");
}
}
}
No comments:
Post a Comment