Reputation: 9
How to find 3 the biggest BigInteger
objects in array? This is my code for now.
package masivi;
import java.math.BigInteger;
import java.util.Scanner;
public class largest3Numbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
BigInteger[] numbers = new BigInteger[n];
BigInteger tempbiggest1 = new BigInteger("0");
BigInteger biggest1 = new BigInteger("0");
BigInteger tempbiggest2 = new BigInteger("0");
BigInteger biggest2 = new BigInteger("0");
BigInteger tempbiggest3 = new BigInteger("0");
BigInteger biggest3 = new BigInteger("0");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scan.nextBigInteger();
if (numbers[i] > tempbiggest1) {
}
}
}
}
Upvotes: 0
Views: 1672
Reputation: 555
Just use Array.sort to sort the array and take the last three elements in the array:
public class SortBigIntegers {
public static void main(String[] args) {
BigInteger[] numbers = new BigInteger[6];
numbers[0] = new BigInteger("10000000");
numbers[1] = new BigInteger("200000000");
numbers[2] = new BigInteger("30000000");
numbers[3] = new BigInteger("5555555555555");
numbers[4] = new BigInteger("6666666666");
numbers[5] = new BigInteger("0");
Arrays.sort(numbers );
System.out.println("the three biggest are: " + numbers[5] + ", " + numbers[4] + ", " + numbers[3]);
}
}
Upvotes: 1
Reputation: 1172
When we use Arrays.sort the elements should be naturally comparable and BigInteger is and implements comparable interface. Thre are few other approaches as well like copying into TreeSet etc but will have more space complexcity.
Upvotes: 0