Question:
how to sort largest number to smallest number in java....?
LISSA
2011-07-31 09:41:04 UTC
input 5 number...then the program will sort like this
input 5 number:
1
2
7
4
3

1st-1
2nd-2
3rd-3
4th-4
5th-7
Three answers:
McFate
2011-07-31 09:43:17 UTC
Put your input numbers into an int[] array. Then call Arrays.sort() on your array and they will be sorted in increasing order. (Edit: You asked for loops, so I did everything with loops. The only challenging thing is to get the "1st" "2nd" etc. right.) Something like this:



===================

import java.util.Scanner;

import java.util.Arrays;



public class MyClass {

static final string suffixes[] = { "st", "nd", "rd", "th", "th" };

public static void main( String[] args ) {



// Get 5 numbers

int numbers[5];

System.out.println("Enter 5 numbers: ");

Scanner sc = new Scanner( System.in );

for (int i=0; i<5; ++i) numbers[i] = sc.nextInt();



// If you are allowed to use Java sort facilities

Arrays.sort( numbers );

// Otherwise, a quick-and-dirty bubble-sort

for (int i=0; i<4; ++i) {

for (int j=0; j<4; ++j) {

if (numbers[j] > numbers[j+1]) {

int tmp = numbers[j+1];

numbers[j+1] = numbers[j];

numbers[j] = tmp;

} } }



// Print them in sorted order

for (int i=0; i<5; ++i)

System.out.println( "" + (i+1) + suffixes[i] + "-" + numbers[i] );

} }

==================
anonymous
2011-07-31 09:49:53 UTC
Try selection sort, that's pretty easy. Don't just use a library function, that's boring and probably not what you're assignment is asking.
anonymous
2011-07-31 09:41:21 UTC
yeds


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...