I was trying to write a Java program to compare previous records while traversing. It returns true if element exists previously, else false.
e.g.
- if elements are
{"Raj","Jas","Kam","Jas"}
then returntrue
(sinceJas
element available previously) - if elements are
{"Raj","Jas","Kam","Tas"}
then returnfalse
I have written the below code, but its complexity is n*n
, which is not good. How could I write clean code to improve the performance?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CompareList {
private List<String> listNames;
private List<String> listTempName = new ArrayList<>();
public CompareList(String[] vListArray) {
listNames = Arrays.asList(vListArray);
}
public CompareList(List<String> vListName) {
listNames = vListName;
}
public boolean isPreviousNameExist() {
String tempName = null;
for (int i = 0; i < listNames.size(); i++) {
tempName = listNames.get(i);
if (listTempName.contains(tempName)) {
return true;
} else {
listTempName.add(tempName);
}
}
return false;
}
public static void main(String[] args) {
String[] nameArray = {"A", "B", "C", "D", "E", "F"};
CompareList compareList = new CompareList(nameArray);
System.out.println("==>" + compareList.isPreviousNameExist());
}
}
UPDATED
I have updated the code and tried using a recursive way, same way how we sort using MergeSort and find its performance better for a large number of records, compared to HashSet. I believe its complexity is O(log n).
public class NameComparator {
private String[] listNames;
private String[] listTempNames;
private boolean compareFlag = false;
private int size;
public boolean isNameAlreadyExist(String[] vListNames) {
this.listNames = vListNames;
size = vListNames.length;
this.listTempNames = new String[size];
checkAndSort(0, size - 1);
return compareFlag;
}
private void checkAndSort(int low, int high) {
//Use the merge sort
}
}
..............................
}