Skip to content
Advertisement

Create an algorithm that arranges them in order to form the largest possible integer

I am struggling with this coding problem in Java. It has to be solved using an algorithm. It is supposed to give me the largest possible inter that can be formed with the numbers in the array: {10, 7, 76, 415}. I tried to solve it using selection sort. So far I have is this code below but it’s giving me the wrong output. My code:

public class largestNumber { public static int largestNumber(int[] arr) {

JavaScript

}

The given output from this code is:10415767 But the right answer is: 77641510

Please give your feedback and thoughts.

Advertisement

Answer

Fix the bugs as shown below and it should work.

JavaScript

To write some elegant code, I would have used a comparator as shown below:

JavaScript

To talk about time complexity, the two for loops in your code makes this solution O(n^2) whereas with the use of sort it becomes O(nlog(n)) where n is the number of elements in the input array. So, not only the code becomes elegant with the use of comparator, in this case it becomes efficient too.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement