Name and percentage of students – Selection Sort

Write a program to input name and percentage of 35 students of class X in two separate  one dimensional arrays. Arrange students details according to their percentage in the  descending order using selection sort method. Display name and percentage of first  ten toppers of the class.

import java.util.Scanner;
class Students
{
    public static void main(String[] args)
    {
        String n[] = new String[35];
        int p[] = new int[35];
 
        Scanner in = new Scanner(System.in);
        for (int i = 0; i < 35; i++) 
        {
            System.out.print("Enter name " + (i + 1) + ": ");
            n[i] = in.nextLine();
            System.out.print("Enter percentage: ");
            p[i] = in.nextInt();
            in.nextLine();
        }
 
        //selection sort
        int l=p.length;
        for (int i=0; i<l-1; i++) 
        {
            int pos = i;
            for (int j=i+1; j<l; j++) 
            {
                if (p[j] > p[pos]) 
                {
                    pos = j;
                }
            }
            // Swap percentage
            int t1 = p[pos];
            p[pos] = p[i];
            p[i] = t1;
            // Swap name
            String t2 = n[pos];
            n[pos] = n[i];
            n[i] = t2;
        }
 
        // Print top 10 Students
        System.out.println("RANK \t NAME \t PERCENTAGE");
        for (int i = 0; i < 10; i++)
        {
            System.out.println((i+1) + " \t " + n[i] + " \t " + p[i]);
        }
    }
}

Video Explanation

Leave a Comment

Your email address will not be published. Required fields are marked *