I need logic to think the solution of this code this is entirely out of my mind
Incapable of thinking the logic
A simple solution that comes to our mind is to sort all numbers in descending order, but simply sorting doesn’t work.
For example, 548 is greater than 60, but in output 60 comes before 548. As a second example, 98 is greater than 9, but 9 comes before 98 in output.
So how do we go about it?
The idea is to use any comparison based sorting algorithm.
In the used sorting algorithm, instead of using the default comparison, write a comparison function myCompare() and use it to sort numbers.
Given two numbers X and Y, how should myCompare() decide which number to put first – we compare two numbers XY (Y appended at the end of X) and YX (X appended at the end of Y).
If XY is larger, then X should come before Y in output, else Y should come before. For example, let X and Y be 542 and 60. To compare X and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put Y first.
Yes the logic is clear now… But how to append the data in given in array??
In the solution you wrote ki You need to append X and Y (this line-we compare two numbers XY (Y appended at the end of X) and YX (X appended at the end of Y).) how to perform these operation on array element
public static int compare(int n1, int n2) {
String val1 = n1 + "" + n2;
String val2 = n2 + "" + n1;
int val1int = Integer.valueOf(val1);
int val2int = Integer.valueOf(val2);
if (val1int > val2int)
return -1;
else
return 1;
}
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
https://ide.codingblocks.com/s/299477 my code is compiling right but giving run error in all test cases
great thanks I understood… I have one doubt at last… whether using functions helps to decrease time complexity??
@HemantNasa,
Time complexity doesn’t depend on the number of functions. In recursive functions it does. But it depends on the loops usually.
Like:
function_call (int k)
{
for(i=0;i<k;i++)
\\some work being done.
}
main {
for(i=0;i<n;i++)
for(j=0;j<n;j++)
function_call(j)
}
Now in such a scenario number of functions will increase the time complexity.
Hence, time complexity depends on the total work being done in the code.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.