Welcome to ICSE Java Answers. Ask any questions you have related to Java and we will answer them.
Java is a registered trademark of Oracle. This site is in no way related to or endorsed by Oracle.

Accept name and percentage of students and sort using using selection sort

0 votes
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.
asked by anonymous
edited by Ranjith

1 Answer

0 votes

Program

import java.util.Scanner;

public class Marks {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] names = new String[35];
        int[] percentages = new int[35];
        for (int i = 0; i < 35; i++) {
            System.out.print("Enter name of student " + (i + 1) + ": ");
            names[i] = scanner.nextLine();
            System.out.print("Enter percentage of student " + (i + 1) + ": ");
            percentages[i] = scanner.nextInt();
            scanner.nextLine(); // To skip the empty line after entering a number
        }
        for (int i = 0; i < percentages.length - 1; i++) {
            int maxIndex = i;
            for (int j = i + 1; j < percentages.length; j++) {
                if (percentages[j] > percentages[maxIndex]) {
                    maxIndex = j;
                }
            }

            int tempMarks = percentages[maxIndex];
            percentages[maxIndex] = percentages[i];
            percentages[i] = tempMarks;

            String tempName = names[maxIndex];
            names[maxIndex] = names[i];
            names[i] = tempName;
        }

        System.out.println("First 10 toppers: ");
        for (int i = 0; i < 10; i++) {
            System.out.println(names[i] + ": " + percentages[i]);
        }
    }
}

Sample output

Enter name of student 1: S1
Enter percentage of student 1: 89
Enter name of student 2: S2
Enter percentage of student 2: 50
Enter name of student 3: S3
Enter percentage of student 3: 100
Enter name of student 4: S4
Enter percentage of student 4: 56
Enter name of student 5: S5
Enter percentage of student 5: 59
...
Top 10 toppers: 
S3: 100
S1: 89
S5: 59
...

 

answered by Ranjith (2,683 points)
...