Write a Java program to form the largest number from a given list of non-negative integers.
Example:
Input :
nums = {1, 2, 3, 0, 4, 6}
Output:
Largest number using the given array numbers: 643210
public class Main {
public static void main(String[] args) {
//define original array
int [] intArray = new int [] {1,2,3,0,4,6};
int temp = 0;
//print original array
System.out.println("Original array: ");
for (int i = 0; i <intArray.length; i++) {
System.out.print(intArray[i] + " ");
}
//Sort the array in ascending order using two for loops
for (int i = 0; i <intArray.length; i++) {
for (int j = i+1; j <intArray.length; j++) {
if(intArray[i] >intArray[j]) { //swap elements if not in order
temp = intArray[i];
intArray[i] = intArray[j];
intArray[j] = temp;
}
}
}
//print sorted array
System.out.println("\nArray sorted in ascending order: ");
for (int i = 0; i <intArray.length; i++) {
System.out.print(intArray[i] + " ");
}
}
}
Comments
Leave a comment