i want to create Java program that accepts 3 numbers (num1, num2, num3) and sort them in ascending and descending order.


Example:

Enter num1: 8
Enter num2: 3
Enter num3: 9

Ascending: 3, 8, 9
Descending: 9,8,3

can anyone help me for this

(sorry for my bad English)

Recommended Answers

All 2 Replies

There are many sorting algorithms, one of the best one is quick sort and the easiest one is bubble sort. If you are going to have more than 3 numbers to sort, you could imlement one of this algorithms or even better, just use the existing ones: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Arrays.html

However, if you need to sort only 3 numbers you could do something like this:

import java.util.Arrays;

int a, b, c;

int[] arr = {a,b,c};
arr.sort(); // that would sort it in ascending order;

// for descending order visit the link I posted above and you probably will find what you need for descending order ;)
import java.util.*;

public class Sorting {
    public static void main(String[] args){
     
     Scanner sc = new Scanner(System.in);
     TreeSet<Integer> ts = new TreeSet<Integer>();
     for(int i = 0;i<3;i++){
         System.out.print("Enter num"+(i+1)+" : ");
         ts.add(sc.nextInt());
     }

     System.out.println("Ascending : "+ts);
     System.out.println("Descending : "+ts.descendingSet());

    }

}

Try the above code

gud time:
mahkris

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.