Selection Sort in String Program in Java

Selection Sort in String Program in Java
Selection Sort in String Program in Java

Write a program to input the names of 15 cities sort in descending order using selection sort technique.

import java.util.Scanner;
public class SelectionSortString
{
    public static void main(String[] args)
    {
        String cities[] = new String[15];
        Scanner sc = new Scanner(System.in);
        int l = cities.length;
        System.out.println("Enter 15 cities name:");
        for (int i = 0; i < l; i++)
        {
             cities[i]=sc.nextLine();
        }
        System.out.println();
        for (int i = 0; i < l - 1; i++)
        {
            int min = i;
            String st = cities[i];
            for (int j = i + 1; j < l; j++)
            {
                if (cities[j].compareTo(st) > 0)
                {
                    st = cities[j];
                    min = j;
                }
            }
            if (min != i)
            {
                String temp = cities[min];
                cities[min] = cities[i];
                cities[i] = temp;
            }
        }
        System.out.println("Sorted cities name:");
        for (int i = 0; i < l; i++)
        {
            System.out.println(cities[i]);
        }
    }
}

Output:

Enter 15 cities name:
Delhi
Mumbai
Kolkata
Chennai
Varanasi
Lucknow
Kanpur
Patna
Jaunpur
Prayag Raj
Aligarh
Noida
Ahmdabad
Banglore
Pune

Sorted cities name:
Varanasi
Pune
Prayag Raj
Patna
Noida
Mumbai
Lucknow
Kolkata
Kanpur
Jaunpur
Delhi
Chennai
Banglore
Aligarh
Ahmdabad
java java string sorting string array
Recent Posts