I'm working on this project using Arrays. I have a method called createRandomIntArray that creates an array. This method is meant to return the Array in descending order. I have been able to do just that but I want to know if there is a more effective way to write this method than the way I wrote it. I have my code below.
public static int[] createRandomIntArray(int n) {
Random random = new Random();
int[] result = new int[n];
for (int i = 0; i < n; i ) {
result[i] = random.nextInt(n);
}
Arrays.sort(result);
for (int i = 0; i < result.length / 2; i ) {
int temp = result[i];
result[i] = result[result.length - i - 1];
result[result.length - i - 1] = temp;
}
return result;
}
CodePudding user response:
You could avoid reversing the sorted array by directly sorting reverse order:
Arrays.sort(result, Comparator.reverseOrder());
As mentioned in the comments one could use Random.ints(…)
if you’re not tied to using arrays:
random.ints(n, 0, n).boxed().sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray(int[]::new);
CodePudding user response:
public class SortDes {
public static void main(String[] args) {
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i ) {
System.out.print(arr[i] " ");
}
for (int i = 0; i < arr.length; i ) {
for (int j = i 1; j < arr.length; j ) {
if(arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i ) {
System.out.print(arr[i] " ");
}
}
}
CodePudding user response:
There's an alternative which is using Stream
.
Arrays.stream(result).sorted(Comparator.reverseOrder());
CodePudding user response:
Using Java Streams
private static int[] createRandomIntArray(int n) {
return ThreadLocalRandom.current().ints() // Stream of random ints
.limit(n) // Limit the stream to n values
.boxed() // Convert to Stream of Integer Objects for reverse sorting
.sorted(Collections.reverseOrder()) // Sort in reverse Order
.mapToInt(Integer::intValue) // Map back to primitive ints
.toArray(); // as Array
}