Sort an Array in Java

Sort an array in 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();

java Arrays.sort 2d array

Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.

double[][] array= {
{1, 5},
{13, 1.55},
{12, 100.6},
{12.1, .85} };

java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
public int compare(double[] a, double[] b) {
return Double.compare(a[0], b[0]);
}
});

JAVA-8: Instead of that big comparator, we can use lambda function as following-

Arrays.sort(array, Comparator.comparingDouble(o -> o[0]));

How to sort an array of objects in Java?

You have two ways to do that, both use the Arrays utility class

  1. Implement a Comparator and pass your array along with the comparator to the sort method which take it as second parameter.
  2. Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.

Example

class Book implements Comparable<Book> {
public String name, id, author, publisher;
public Book(String name, String id, String author, String publisher) {
this.name = name;
this.id = id;
this.author = author;
this.publisher = publisher;
}
public String toString() {
return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")");
}
@Override
public int compareTo(Book o) {
// usually toString should not be used,
// instead one of the attributes or more in a comparator chain
return toString().compareTo(o.toString());
}
}

@Test
public void sortBooks() {
Book[] books = {
new Book("foo", "1", "author1", "pub1"),
new Book("bar", "2", "author2", "pub2")
};

// 1. sort using Comparable
Arrays.sort(books);
System.out.println(Arrays.asList(books));

// 2. sort using comparator: sort by id
Arrays.sort(books, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o1.id.compareTo(o2.id);
}
});
System.out.println(Arrays.asList(books));
}

Output

[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]
[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]

Java Array Sort descending?

You could use this to sort all kind of Objects

sort(T[] a, Comparator<? super T> c) 

Arrays.sort(a, Collections.reverseOrder());

Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If you try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder() , it will throw the error

no suitable method found for sort(int[],comparator)

That will work fine with 'Array of Objects' such as Integer array but will not work with a primitive array such as int array.

The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place. This is also true for two-dimensional primitive arrays.

Fastest way to sort an array without overwriting it

You could use

int[] a2 = IntStream.of(a).sorted().toArray();

But I doubt it's faster than

int[] a2 = a.clone();
Arrays.sort(a2);

Regardless it's the same complexity, so don't expect more than a constant factor speedup.

Sorting an array by number of digits in each element from largest to smallest using loops java

The easiest way to find the length of the number is to convert it into a String and then call the method length on it.

int number = 123;
String numberAsString = String.valueOf(number);
int length = numberAsString.length(); // returns 3

But you also could do it by division. The following method takes a number and divides by multiples of 10.

  • divide by 1 (we have at least a length of 1)
  • division by 10 > 0 (we have at least a length of 2)
  • division by 100 > 0 (we have at least a length of 3)
  • ...

the variable i is used as dividend and the variable j is used as counter. j counts the length of the number.

As soon as number / i equals zero we return the counter value.

public int lengthOfNumber(int number) {
if (number == 0) {
return 1;
}
for (int i = 1, j = 0; ; i *= 10, j++) {
if (number / i == 0) {
return j;
}
}
}

There are multiple ways to sort the array. Here are some examples (I used the string version for comparing the values).

Use nested for-loop

public void sortArray(int[] array) {
for (int i = 0; i < array.length; i++) {
int swapIndex = -1;
int maxLength = String.valueOf(array[i]).length();
for(int j = i + 1; j < array.length; j++) {
int length2 = String.valueOf(array[j]).length();
if (maxLength < length2) {
maxLength = length2;
swapIndex = j;
}
}

if (swapIndex > -1) {
int temp = array[i];
array[i] = array[swapIndex];
array[swapIndex] = temp;
}
}
}

I used a variable swapIndex which is initialized with -1. This way we can avoid unnecessary array operations.
We take the first element in the outer for-loop and go through the rest of the array in the inner for-loop. we only save a new swapIndex if there is a number in the rest of the array with a higher length. if there is no number with a higher length, swapIndex remains -1. We do a possible swap only in the outer for-loop if necessary (if swapIndex was set).

Using Arrays.sort()

If you want to use Arrays.sort you need to convert your array from primitive type int to Integer.

public void sortArray(Integer[] array) {
Arrays.sort(array, (o1, o2) -> {
Integer length1 = String.valueOf(o1).length();
Integer length2 = String.valueOf(o2).length();
return length2.compareTo(length1);
});
}

Using a recursive method

public void sortArray(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
String current = String.valueOf(array[i]);
String next = String.valueOf(array[i + 1]);

if (current.length() < next.length()) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;

// here you do a recursive call
sortArray(array);
}
}
}


Related Topics



Leave a reply



Submit