Compare 2 arrays

I have 2 vectors containing String objects

I need to determine whether each String present in the first Vector is present in the 2nd Vector or not

Is there anyways to to this such that its complexity is less than O(n^2) i.e Order(n square)

The result obtained should be fast as this is algorithm is to be used in a real-time user application

Plz help

[381 byte] By [aneez_backera] at [2007-10-2 23:02:10]
# 1
try thisboolean result = myVector1.containsAll(myVector2);see the javadoc for java.util.Vector#contains(Collection)I'm not sure what the time complexity of this approach is
jspflya at 2007-7-14 6:16:13 > top of Java-index,Other Topics,Algorithms...
# 2

java.util.Vector#contains(Collection) appears to be O(n^2). Running this with 2 Vectors containing strings "0","1",..."9999" takes 1.344 s on my computer. Converting the other Vector to a sorted array and using binary search takes 0.015 s...

import java.util.*;

class Test {

static Vector createTestVector(int n) {

Vector res = new Vector();

for(int i=0; i<n; i++) res.add(i+"");

return res;

}

static boolean containsAll(Vector a, Vector b) {

String[] x = new String[b.size()];

x = (String[])b.toArray(x);

Arrays.sort(x);

for(int i=0; i<a.size(); i++) if(search(x,(String)a.get(i))<0) return false;

return true;

}

private static int search(String[] array, String item) {

int start = 0, end = array.length, mid;

while(start<end) {

mid = (start + end)/2;

int test = array[mid].compareTo(item);

if(test==0) return mid;

if(test<0) start = mid + 1;

else end = mid;

}

return -1;

}

public static void main(String[] args) {

Vector a = createTestVector(10000), b = a;

boolean same = false;

long now = System.currentTimeMillis();

//same = a.containsAll(b);

same = containsAll(a,b);

now = System.currentTimeMillis() - now;

System.out.println(same + " " + (now/1000.0));

}

}

Message was edited by:

perkele

perkelea at 2007-7-14 6:16:13 > top of Java-index,Other Topics,Algorithms...
# 3
stuff the elements from the first vector into a hash set.look to see if the elements of the second vector are in the hash set.Insertion into hash set is O(1) - inserting N element is O(N)find in hash set is O(1) - finding N elements is O(N) Total complexity:
marlin314a at 2007-7-14 6:16:13 > top of Java-index,Other Topics,Algorithms...
# 4
Average is O(N), worst case is O(N^2). In practice for your strings, it might be quicker than the sorting method however.Gil
gilroittoa at 2007-7-14 6:16:13 > top of Java-index,Other Topics,Algorithms...
# 5

All all elements from the 2nd vector into a trie.

Then for each element in the 1st vector check to see if the trie contains it.

http://www.graphbuilder.com/trie/

This approach should be O(n + m) where n is the number of the characters in the first vector and m is the number f the characters in the second vector.

rkippena at 2007-7-14 6:16:13 > top of Java-index,Other Topics,Algorithms...