ALGORITHM:
This problem can be simply solved by changing the comparison criteria of any sorting algorithms.
Comparison should be changed as explained
if the two numbers to be compared are a & b then two numbers should be made tempA and tempB such that:
tempA = a*10^(number of digits in b)+b
tempB = b*10^(number of digits in a)+a
if tempA>tempB then a is larger than b and vice versa
Code of the above logic implemented with bubble sort is given below:
tempA = a*10^(number of digits in b)+b
tempB = b*10^(number of digits in a)+a
if tempA>tempB then a is larger than b and vice versa
Code of the above logic implemented with bubble sort is given below:
CODE:
import java.util.Scanner;
class maxNo{
static int size(int a){ //simple utility function count no of digits
int count=0;
do{
count++;
a/=10;
}while(a!=0);
return count;
}
//utility function to implement modified comparison criteria of the sort
static int[] compare(int[] a,int i,int j){
double t1,t2;
int tmp;
t1=a[i]*Math.pow(10,size(a[j]))+a[j];
t2=a[j]*Math.pow(10,size(a[i]))+a[i];
if(t1<t2){
tmp=a[i]; //swapping ith and jth elements
a[i]=a[j];
a[j]=tmp;
}
return a;
}
static int[] bubSort(int[] a,int size){ //simple bubble sort with comparison criteria changed
int i,j;
for(i=0;i<size-1;i++)
for(j=0;j<size-i-1;j++)
a=compare(a,j,j+1);
return a;
}
//driver function
public static void main(String[] args) {
int n,i;
Scanner in = new Scanner(System.in);
System.out.print("\nEnter size of array:");
n=in.nextInt();
int[] ar = new int[n];
System.out.println("Enter the array:");
for (i=0;i<n;i++)
ar[i]=in.nextInt();
ar=bubSort(ar,n);
System.out.println("Maximum num made from the array is:");
for (i=0;i<n;i++)
System.out.print(ar[i]);
}
}
class maxNo{
static int size(int a){ //simple utility function count no of digits
int count=0;
do{
count++;
a/=10;
}while(a!=0);
return count;
}
//utility function to implement modified comparison criteria of the sort
static int[] compare(int[] a,int i,int j){
double t1,t2;
int tmp;
t1=a[i]*Math.pow(10,size(a[j]))+a[j];
t2=a[j]*Math.pow(10,size(a[i]))+a[i];
if(t1<t2){
tmp=a[i]; //swapping ith and jth elements
a[i]=a[j];
a[j]=tmp;
}
return a;
}
static int[] bubSort(int[] a,int size){ //simple bubble sort with comparison criteria changed
int i,j;
for(i=0;i<size-1;i++)
for(j=0;j<size-i-1;j++)
a=compare(a,j,j+1);
return a;
}
//driver function
public static void main(String[] args) {
int n,i;
Scanner in = new Scanner(System.in);
System.out.print("\nEnter size of array:");
n=in.nextInt();
int[] ar = new int[n];
System.out.println("Enter the array:");
for (i=0;i<n;i++)
ar[i]=in.nextInt();
ar=bubSort(ar,n);
System.out.println("Maximum num made from the array is:");
for (i=0;i<n;i++)
System.out.print(ar[i]);
}
}
OUTPUT:
Enter size of array:5
Enter the array:
1 10 11 100 110
Maximum num made from the array is:
11111010100
Enter the array:
1 10 11 100 110
Maximum num made from the array is:
11111010100