Sort an array in Java
JavaArraysJava Problem Overview
I'm trying to make a program that consists of an array of 10 integers which all has a random value, so far so good.
However, now I need to sort them in order from lowest to highest value and then print it onto the screen, how would I go about doing so?
(Sorry for having so much code for a program that small, I ain't that good with loops, just started working with Java)
public static void main(String args[])
{
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
+" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" "
+ array[8]+" " + array[9] );
}
Java Solutions
Solution 1 - Java
Loops are also very useful to learn about, esp When using arrays,
int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++)
array[i] = rand.nextInt(100) + 1;
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// in reverse order
for (int i = array.length - 1; i >= 0; i--)
System.out.print(array[i] + " ");
System.out.println();
Solution 2 - Java
Add the Line before println and your array gets sorted
Arrays.sort( array );
Solution 3 - Java
It may help you understand loops by implementing yourself. See Bubble sort is easy to understand:
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
Of course, you should not use it in production as there are better performing algorithms for large lists such as QuickSort or MergeSort which are implemented by Arrays.sort(array)
Solution 4 - Java
Take a look at Arrays.sort()
Solution 5 - Java
I was lazy and added the loops
import java.util.Arrays;
public class Sort {
public static void main(String args[])
{
int [] array = new int[10];
for ( int i = 0 ; i < array.length ; i++ ) {
array[i] = ((int)(Math.random()*100+1));
}
Arrays.sort( array );
for ( int i = 0 ; i < array.length ; i++ ) {
System.out.println(array[i]);
}
}
}
Your array has a length of 10. You need one variable (i
) which takes the values from 0
to 9
.
for ( int i = 0 ; i < array.length ; i++ )
^ ^ ^
| | ------ increment ( i = i + 1 )
| |
| +-------------------------- repeat as long i < 10
+------------------------------------------ start value of i
Arrays.sort( array );
Is a library methods that sorts arrays.
Solution 6 - Java
Arrays.sort(yourArray)
will do the job perfectly
Solution 7 - Java
For natural order : Arrays.sort(array)
For reverse Order : Arrays.sort(array, Collections.reverseOrder());
-- > It is a static method in Collections class which will further call an inner class of itself to return a reverse Comparator.
Solution 8 - Java
See below, it will give you sorted ascending and descending both
import java.util.Arrays;
import java.util.Collections;
public class SortTestArray {
/**
* Example method for sorting an Integer array
* in reverse & normal order.
*/
public void sortIntArrayReverseOrder() {
Integer[] arrayToSort = new Integer[] {
new Integer(48),
new Integer(5),
new Integer(89),
new Integer(80),
new Integer(81),
new Integer(23),
new Integer(45),
new Integer(16),
new Integer(2)
};
System.out.print("General Order is : ");
for (Integer i : arrayToSort) {
System.out.print(i.intValue() + " ");
}
Arrays.sort(arrayToSort);
System.out.print("\n\nAscending Order is : ");
for (Integer i : arrayToSort) {
System.out.print(i.intValue() + " ");
}
Arrays.sort(arrayToSort, Collections.reverseOrder());
System.out.print("\n\nDescinding Order is : ");
for (Integer i : arrayToSort) {
System.out.print(i.intValue() + " ");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SortTestArray SortTestArray = new SortTestArray();
SortTestArray.sortIntArrayReverseOrder();
}}
Output will be
General Order is : 48 5 89 80 81 23 45 16 2
Ascending Order is : 2 5 16 23 45 48 80 81 89
Descinding Order is : 89 81 80 48 45 23 16 5 2
Note: You can use Math.ranodm instead of adding manual numbers. Let me know if I need to change the code...
Good Luck... Cheers!!!
Solution 9 - Java
int[] array = {2, 3, 4, 5, 3, 4, 2, 34, 2, 56, 98, 32, 54};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] < array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
Solution 10 - Java
You can sort a int array with Arrays.sort( array )
.
Solution 11 - Java
Here is how to use this in your program:
public static void main(String args[])
{
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
Arrays.sort(array);
System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
+" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" "
+ array[8]+" " + array[9] );
}
Solution 12 - Java
just FYI, you can now use Java 8 new API for sorting any type of array using parallelSort
parallelSort
uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool.
the two methods that can be used to sort int
array,
parallelSort(int[] a)
parallelSort(int[] a,int fromIndex,int toIndex)
Solution 13 - Java
Java 8 provides the option of using streams which can be used to sort int[] array
as:
int[] sorted = Arrays.stream(array).sorted().toArray(); // option 1
Arrays.parallelSort(array); //option 2
As mentioned in [doc][1] for parallelSort
:
> The sorting algorithm is a parallel sort-merge that breaks the array > into sub-arrays that are themselves sorted and then merged. When the > sub-array length reaches a minimum granularity, the sub-array is > sorted using the appropriate Arrays.sort method. If the length of the > specified array is less than the minimum granularity, then it is > sorted using the appropriate Arrays.sort method. The algorithm > requires a working space no greater than the size of the original > array. The ForkJoin common pool is used to execute any parallel tasks.
So if the input array is less than granularity (8192 elements in Java 9 and 4096 in Java 8 I believe), then parallelSort
simply calls sequential sort algorithm.
Just in case we want to reverse sort the integer array we can make use of comparator as:
int[] reverseSorted = IntStream.of(array).boxed()
.sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
Since Java has no way to sort primitives with custom comparator, we have to use intermediate boxing or some other third party library which implements such primitive sorting. [1]: https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#parallelSort-int:A-
Solution 14 - Java
You may use Arrays.sort() function.
sort() method is a java.util.Arrays class method.
Declaration : Arrays.sort(arrName)
Solution 15 - Java
Simply do the following before printing the array:-
Arrays.sort(array);
Note:- you will have to import the arrays class by saying:-
import java.util.Arrays;
Solution 16 - Java
If you want to build the Quick sort algorithm yourself and have more understanding of how it works check the below code :
1- Create sort class
class QuickSort {
private int input[];
private int length;
public void sort(int[] numbers) {
if (numbers == null || numbers.length == 0) {
return;
}
this.input = numbers;
length = numbers.length;
quickSort(0, length - 1);
}
/*
* This method implements in-place quicksort algorithm recursively.
*/
private void quickSort(int low, int high) {
int i = low;
int j = high;
// pivot is middle index
int pivot = input[low + (high - low) / 2];
// Divide into two arrays
while (i <= j) {
/**
* As shown in above image, In each iteration, we will identify a
* number from left side which is greater then the pivot value, and
* a number from right side which is less then the pivot value. Once
* search is complete, we can swap both numbers.
*/
while (input[i] < pivot) {
i++;
}
while (input[j] > pivot) {
j--;
}
if (i <= j) {
swap(i, j);
// move index to next position on both sides
i++;
j--;
}
}
// calls quickSort() method recursively
if (low < j) {
quickSort(low, j);
}
if (i < high) {
quickSort(i, high);
}
}
private void swap(int i, int j) {
int temp = input[i];
input[i] = input[j];
input[j] = temp;
}
}
2- Send your unsorted array to Quicksort
class
import java.util.Arrays;
public class QuickSortDemo {
public static void main(String args[]) {
// unsorted integer array
int[] unsorted = {6, 5, 3, 1, 8, 7, 2, 4};
System.out.println("Unsorted array :" + Arrays.toString(unsorted));
QuickSort algorithm = new QuickSort();
// sorting integer array using quicksort algorithm
algorithm.sort(unsorted);
// printing sorted array
System.out.println("Sorted array :" + Arrays.toString(unsorted));
}
}
3- Output
Unsorted array :[6, 5, 3, 1, 8, 7, 2, 4]
Sorted array :[1, 2, 3, 4, 5, 6, 7, 8]
Solution 17 - Java
We can also use binary search tree for getting sorted array by using in-order traversal method. The code also has implementation of basic binary search tree below.
class Util {
public static void printInorder(Node node)
{
if (node == null) {
return;
}
/* traverse left child */
printInorder(node.left);
System.out.print(node.data + " ");
/* traverse right child */
printInorder(node.right);
}
public static void sort(ArrayList<Integer> al, Node node) {
if (node == null) {
return;
}
/* sort left child */
sort(al, node.left);
al.add(node.data);
/* sort right child */
sort(al, node.right);
}
}
class Node {
Node left;
Integer data;
Node right;
public Node(Integer data) {
this.data = data;
}
public void insert(Integer element) {
if(element.equals(data)) {
return;
}
// if element is less than current then we know we will insert element to left-sub-tree
if(element < data) {
// if this node does not have a sub tree then this is the place we insert the element.
if(this.left == null) {
this.left = new Node(element);
} else { // if it has left subtree then we should iterate again.
this.left.insert(element);
}
} else {
if(this.right == null) {
this.right = new Node(element);
} else {
this.right.insert(element);
}
}
}
}
class Tree {
Node root;
public void insert(Integer element) {
if(root == null) {
root = new Node(element);
} else {
root.insert(element);
}
}
public void print() {
Util.printInorder(root);
}
public ArrayList<Integer> sort() {
ArrayList<Integer> al = new ArrayList<Integer>();
Util.sort(al, root);
return al;
}
}
public class Test {
public static void main(String[] args) {
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
Tree tree = new Tree();
for (int i = 0; i < array.length; i++) {
tree.insert(array[i]);
}
tree.print();
ArrayList<Integer> al = tree.sort();
System.out.println("sorted array : ");
al.forEach(item -> System.out.print(item + " "));
}
}
Solution 18 - Java
MOST EFFECTIVE WAY!
public static void main(String args[])
{
int [] array = new int[10];//creates an array named array to hold 10 int's
for(int x: array)//for-each loop!
x = ((int)(Math.random()*100+1));
Array.sort(array);
for(int x: array)
System.out.println(x+" ");
}
Solution 19 - Java
Be aware that Arrays.sort() method is not thread safe: if your array is a property of a singleton, and used in a multi-threaded enviroment, you should put the sorting code in a synchronized block, or create a copy of the array and order that copy (only the array structure is copied, using the same objects inside).
For example:
int[] array = new int[10];
...
int[] arrayCopy = Arrays.copyOf(array , array .length);
Arrays.sort(arrayCopy);
// use the arrayCopy;