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

Tuesday 9 April 2019

Generic Storing of Number

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

Solution:

public class Students{

   public static <T extends Comparable<T>> void sortingMethod(Number[] i2)   {

    int i,j,n;

    n=i2.length;

    for(i=0;i<n;i++)

     for(j=0;j<n-i-1;j++)

      if(((Comparable<T>) i2[j]).compareTo((T) i2[j+1])>0)

      {

       T temp;

       temp=(T) i2[j];

       i2[j]=i2[j+1];

       i2[j+1]=(Number) temp;

      }

    System.out.println();

    System.out.println("After Sorting The Elements");

    for(Number element: i2)

    System.out.printf("%s, ", element);

   }

   public static void main(String args[])

   {

    Number i[]={3.2,2.5,10.02,7.012,7.06};

    System.out.println("Before Sorting The Elements");

    for(Number element:i)

     System.out.printf("%s, ",element);

    sortingMethod(i);

   }



}





Output:

Before Sorting The Elements

3.2, 2.5, 10.02, 7.012, 7.06, 

After Sorting The Elements

2.5, 3.2, 7.012, 7.06, 10.02, 



Credits: Gaurav

0 comments:

Post a Comment