Program to read N different strings from user and sort it in Java

 



Code:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of string you want to sort: ");
        int n = sc.nextInt();
                
        String str[] = new String[n];
        String temp;
        int i, j;
        
        System.out.println("Enter all strings:");
        for(i = 0; i < str.length; i++)
        {
            str[i] = sc.next();
        }
        
        for(i = 0; i < str.length; i++)
        {
            for(j = i + 1; j < str.length; j++)
            {
                if((str[i].compareTo(str[j])) > 0)
                {
                    temp = str[i];
                    str[i] = str[j];
                    str[j] = temp;
                }
            }
        }
        System.out.println("\nSorted strings:");
        for(i = 0; i < str.length; i++)
        {
            System.out.println(str[i]);
        }
    }
}


Output:

AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page