Created
May 6, 2015 00:02
-
-
Save chinying/fa6a6ac08fca88348eb7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private Vector<String> mergeSort(Vector<String> v){ | |
int sz = v.size(); | |
if (sz > 1){ | |
int m = sz >>> 1; | |
Vector<String> leftList = new Vector<String>(); | |
Vector<String> rightList = new Vector<String>(); | |
int n; | |
for (n=0; n<m; n++) leftList.add(v.elementAt(n)); | |
for (n=m; n<sz; n++) rightList.add(v.elementAt(n)); | |
leftList = mergeSort(leftList); | |
rightList = mergeSort(rightList); | |
int x = leftList.size(); | |
int y = rightList.size(); | |
int i=0, j=0, k=0; | |
Vector<String> result = new Vector<String>(); | |
while (i<x && j<y){ | |
if ( (leftList.elementAt(i)).compareTo(rightList.elementAt(j)) < 0){ | |
result.add(leftList.elementAt(i)); | |
i++; | |
} else { | |
result.add(rightList.elementAt(j)); | |
j++; | |
} | |
} | |
while (i<x){ | |
result.add(leftList.elementAt(i)); | |
i++; | |
} | |
while (j<y){ | |
result.add(rightList.elementAt(j)); | |
j++; | |
} | |
v = result; | |
} | |
return v; | |
} | |
private int binarySearch(Vector<String> v, int l, int r, String key){ // returns index, if not found will return insert position | |
int mid; | |
//System.out.println("searching"); | |
while (l<=r){ | |
mid = (l+r) >>> 1; | |
//System.out.printf("Mid: %d \n", mid); | |
if ((v.elementAt(mid)).equals(key)) return mid; | |
else if ((v.elementAt(mid)).compareTo(key) < 0) l = mid+1; | |
else r = mid-1; //not able to find last | |
} | |
return -(l+1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment