Encera :
I've just started programming around 2 weeks ago so please don't be too strict :)
I tried to solve a programming exercise to print the 3 largest elememts of an Array but the .sort Method
reports an error and I don't know why. It seems like I have declared my Array in the wrong way but I can't spot the mistake.
public static void main(String[] args) {
int [] elements = {1, 4, 17, 7, 25, 3, 100};
int k = 3;
System.out.println("Original Array: ");
System.out.println(Arrays.toString(elements));
System.out.println(k +" largest elements of the said array are:");
Arrays.sort(elements, Collections.reverseOrder());
for (int i = 0; i < k; i++)
System.out.print(elements[i] + " ");
}
}
Nexevis :
The other answers addressed on how to reverse your primitive int
array, but according to your problem question, it seems you do not need to reverse the array at all.
Simply iterate through your array beginning at the end by changing your for
conditions:
public static void main(String[] args)
{
int [] elements = {1, 4, 17, 7, 25, 3, 100};
int k = 3;
System.out.println("Original Array: ");
System.out.println(Arrays.toString(elements));
System.out.println(k +" largest elements of the said array are:");
Arrays.sort(elements);
for (int i = elements.length - 1; i > elements.length - k; i--)
System.out.print(elements[i] + " ");
}
Output:
Original Array:
[1, 4, 17, 7, 25, 3, 100]
3 largest elements of the said array are:
100 25 17
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=218356&siteId=1