Wednesday 7 May 2014

Sort Integer array without using sort() method -Java

Hi Viewers


        This post is regarding a small code snippet which helps us to sort an integer array of elements   without using any of the sort() method present in Arrays or Collections in Java API.We used bubble       sort  technique to sort the integer array.This is being asked frequently in written exams of interviewing process.Hope this code snippet helps you 


Code Begins here:


public class SortIntArray {

 public static void main(String[] args) {
  int[] a={12,4,1,7,10,21,21,18,17,15,5,34,30};
  SortIntArray sia=new SortIntArray();
  int[] des=sia.toDescendingOrder(a);
  int[] asc=sia.toAsscendingOrder(a);
  System.out.println(">>>>>>>>>>>descending order>>>");
  for(int i=0;i<des.length;i++){
   System.out.print(des[i]+"\t");
  }
  System.out.println("");
  System.out.println(">>>>>>>asscending order>>>>>>");
  for(int i=0;i<asc.length;i++){
   System.out.print(asc[i]+"\t");
  }
 }
  public int[] toDescendingOrder(int[] a){
   int[] b=toAsscendingOrder(a);
   int c[]=new int[b.length];
   int j=0;
   for(int i=b.length-1;i>=0;i--){
    c[j]=b[i];
    j++;
   }
 return c;
  }
  public int[] toAsscendingOrder(int[] a){
  int swap;
  for(int i=0;i<a.length-1;i++){
   for(int j=0;j<a.length-1-i;j++){
    if(a[j]>a[j+1]){
     swap=a[j];
     a[j]=a[j+1];
     a[j+1]=swap;
    }
   } 
  }
   return a;
  }
}
output: >>>>>>>>>>>descending order>>>
        34 30 21 21 18 17 15 12 10 7 5 4 1 
        >>>>>>>asscending order>>>>>>
        1 4 5 7 10 12 15 17 18 21 21 30 34

No comments:

Post a Comment