Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Thursday 7 March 2019

Sixth Week Term Work Program 3 [ IA-1 2 B) ]

Question:
Write a Java program the implements a generic sort method using any of the sorting techniques.

public class GenericSorting {
//Modification: Sorting Wrt To String Length.
public static <T extends Comparable<T>> void sortingMethod1(T array[])
   {
   int i,j,n;
   n=array.length;
   for(i=0;i<n;i++)
   for(j=0;j<n-i-1;j++)
   if((((String) array[j]).length())>((String) array[j+1]).length())
   {
   T temp;
   temp=array[j];
   array[j]=array[j+1];
   array[j+1]=temp;
   }
   
   for(T element: array)
  System.out.printf("%s ", element);
   System.out.println();
   }

   public static <T extends Comparable<T>> void sortingMethod(T array[])
   {
   int i,j,n;
   n=array.length;
   for(i=0;i<n;i++)
   for(j=0;j<n-i-1;j++)
   if(array[j].compareTo(array[j+1])>0)
   {
   T temp;
   temp=array[j];
   array[j]=array[j+1];
   array[j+1]=temp;
   }
   
   for(T element: array)
  System.out.printf("%s ", element);
   System.out.println();
   }
   public static void main(String args[])
   {
   Integer i[]={3,2,1,7,6};
           String s[]={"pear","orange","apple"};
   sortingMethod(i);
 sortingMethod(s);
 
 System.out.println("\nSorting As per String Length");
 sortingMethod1(s);
 
   }
}

Output:
1 2 3 6 7 
apple orange pear 

Sorting As per String Length

pear apple orange 

Blue Marked Are Modification Asked By Ma'am In B1 Batch.

0 comments:

Post a Comment