How to sort numbers in an array in java

 


To sort numbers in an array in Java, you can use various sorting algorithms. One of the most straightforward methods is to use the Arrays.sort() method, which is built into Java. Here's an example of how to sort an array of numbers using this method:


import java.util.Arrays;

public class ArraySorting {

public static void main(String[] args) {

int[] numbers = {5, 2, 9, 1, 5, 6};

// Sort the array in ascending order

Arrays.sort(numbers);

System.out.println("Sorted array in ascending order:");

for (int num : numbers) {

System.out.print(num + " ");

}

// If you want to sort in descending order, you can reverse the array

// or implement a custom comparator.

Arrays.sort(numbers);

for (int i = 0; i < numbers.length / 2; i++) {

int temp = numbers[i];

numbers[i] = numbers[numbers.length - 1 - i];

numbers[numbers.length - 1 - i] = temp;

}

System.out.println("\nSorted array in descending order:");

for (int num : numbers) {

System.out.print(num + " ");

}

}

}

}                                                  

n this example, we start with an array of integers, and we use Arrays.sort(numbers) to sort the array in ascending order. If you want to sort in descending order, you can reverse the array by swapping elements, as shown in the code. Alternatively, you can implement a custom comparator and use Arrays.sort() with the comparator to achieve descending order sorting.

You can modify the numbers array or add more elements to test different arrays with this sorting approach.


Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.