C
ck
Hi,
I would like to get opinion from the group members about efficiency of
the program below.
I need to filter an input array of int to obtain an output array which
contains distinct elements of the input array.
That is if my input array is {1,2,43,5,2,4,5,20,2,1} the output should
be {1,2,43,4,5,20}
The condition being I cannot use Collection framework, just use array
to get the most efficient algorithm.
Could you guys please tell me if the following algorithm would be
considered efficient?
public class ArrayUniqueElements {
public static int [] filter (int [] input) {
int [] output = new int[input.length];
output[0]=input[0];
boolean flag=true;
int pos=0;
// iteration for each element in input
for (int i=1;i<input.length;i++){
for(int j=0;j<=i;j++){
if(input==output[j]){
flag=false;
break; // exit out of inner loop on first duplicate element
}
}
if(flag){
output[++pos]=input;
} else
flag=true;
}
int [] tempOutput = new int[pos];
// This for loop is required to filter out default values from the
output
for (int i = 0; i < pos; i++) {
tempOutput=output;
}
return tempOutput;
}
}
I would like to get opinion from the group members about efficiency of
the program below.
I need to filter an input array of int to obtain an output array which
contains distinct elements of the input array.
That is if my input array is {1,2,43,5,2,4,5,20,2,1} the output should
be {1,2,43,4,5,20}
The condition being I cannot use Collection framework, just use array
to get the most efficient algorithm.
Could you guys please tell me if the following algorithm would be
considered efficient?
public class ArrayUniqueElements {
public static int [] filter (int [] input) {
int [] output = new int[input.length];
output[0]=input[0];
boolean flag=true;
int pos=0;
// iteration for each element in input
for (int i=1;i<input.length;i++){
for(int j=0;j<=i;j++){
if(input==output[j]){
flag=false;
break; // exit out of inner loop on first duplicate element
}
}
if(flag){
output[++pos]=input;
} else
flag=true;
}
int [] tempOutput = new int[pos];
// This for loop is required to filter out default values from the
output
for (int i = 0; i < pos; i++) {
tempOutput=output;
}
return tempOutput;
}
}