Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting integers in order lowest to highest java

These numbers are stored in the same integer variable. How would I go about sorting the integers in order lowest to highest?

11367
11358
11421
11530
11491
11218
11789
like image 345
user983246 Avatar asked Oct 16 '11 22:10

user983246


People also ask

How to sort an array of integers in Java?

Instead of writing all of the sorting code, we can also use Arrays.sort () static method. This method takes one integer array as the parameter, and then it sorts all the elements of that array passed as the parameter. The final java program will look like as below :

Which sorting algorithm does Java use in sort?

Which sorting algorithm does Java use in sort ()? Previously, Java’s Arrays.sort method used Quicksort for arrays of primitives and Merge sort for arrays of objects. In the latest versions of Java, Arrays.sort method and Collection.sort () uses Timsort.

How to sort the elements of an array in ascending order?

Java Program to sort the elements of an array in ascending order. In this program, we need to sort the given array in ascending order such that elements will be arranged from smallest to largest. This can be achieved through two loops. The outer loop will select an element, and inner loop allows us to compare selected element with rest...

How to sort an array using comparator in Java?

If you use an Integer [] instead of int [], then you can pass a Comparator as 2nd argument to the sort method. To impose reverse ordering, you can make use of Collections.reverseOrder () method: Show activity on this post. If you have an int [] array, you can sort it using Arrays.sort and then reverse it :


2 Answers

There are two options, really:

  1. Use standard collections, as explained by Shakedown
  2. Use Arrays.sort

E.g.,

int[] ints = {11367, 11358, 11421, 11530, 11491, 11218, 11789};
Arrays.sort(ints);
System.out.println(Arrays.asList(ints));

That of course assumes that you already have your integers as an array. If you need to parse those first, look for String.split and Integer.parseInt.

like image 96
alf Avatar answered Oct 05 '22 03:10

alf


You can put them into a list and then sort them using their natural ordering, like so:

final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list

If the numbers are stored in the same variable, then you'll have to somehow put them into a List and then call sort, like so:

final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...

Collections.sort( list );
// Use the sorted list
  • Collections.sort( List )
like image 41
Nate W. Avatar answered Oct 05 '22 03:10

Nate W.