Wednesday, August 17, 2011

How to sort one dimensional array in java


import java.io.*;
class sortarray
{
 public static void main(String[] arg)
  {
   int n, temp;
   BufferedReader in=new BufferedReader(new  InputStreamReader(System.in));
   int arr[]=new int[30];
    try
    {
 System.out.print("Enter the number of elements of array: ");
      n=Integer.parseInt(in.readLine());
     for(int i=0;i<n;i++)
      {
      System.out.print("Enter the value of"+(i+1)+" th elements of array: ");      
        arr[i]=Integer.parseInt(in.readLine());
      }
      System.out.println("Unsorted array list:");
      for(int i=0;i<n;i++)
      {
       System.out.print("  "+arr[i]);
      }
      for(int i=0;i<n;i++)                       
       {
          for(int j=i+1;j<n;j++)
           {
           if(arr[i]>arr[j])          
            {                  
             temp=arr[i];
              arr[i]=arr[j];
              arr[j]=temp;
             }
           }
        }    
        System.out.println();
        System.out.println("Sorted array list:");
        for(int i=0;i<n;i++)
        {
            System.out.print("  "+arr[i]);
        }
     }
    catch(Exception e){ }
   }
}

Previous Next Home
0 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More