Answer To: import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; public class Main {...
Valupadasu answered on Feb 16 2021
console output.png
Main.java
Main.java
import java.util.Arrays;
import java.util.Objects;
public class Main {
public static void printResults(Object[] arr) {
System.out.println(arr[0] == null ? "Not found" : arr[0].toString());
}
public static void main(String[] args) {
String fileName = "tweet_data_sorted.csv";
Tweet[] tweetArr = TweetLoader.loadAsArray(fileName);
tweetArr = Arrays.stream(tweetArr).filter(Objects::nonNull).toArray(Tweet[]::new); // since we created array dynamically , end of array we have have some null values so removed those
int tweetIdForSearch[] = { 1000, 1005, 1804, 2499, 2504, 2800 };
for (int id : tweetIdForSearch) {
System.out.println("================================");
System.out.println("Finding tweet with Id " + id);
System.out.println("Using linear search");
printResults(SearchObject.linearSearch(tweetArr, tweetArr.length, new Tweet(id, "", "")));
System.out.println("Using binary search");
Arrays.sort(tweetArr); // array to be sorted for binary search
printResults(SearchObject.binarySearch(tweetArr, tweetArr.length, new Tweet(id, "", "")));
}
}
}
SearchObject.java
SearchObject.java
public class SearchObject {
public static Object[] linearSearch(Object[] inputArray, int arraySize, Object searchKey) {
Object[] output = new Object[1];
for(int idx=0; idx < arraySize ; idx++){
if(inputArray[idx].equals(searchKey)){
output[0] = inputArray[idx];
return output;
}
}
return output;
}
public static int binarySearch(Object[] inputArray, Comparable searchKey, int first, int last){
if(first > last)
return -1;
else{
int mid = (first + last) / 2;
int compResult = searchKey.compareTo(inputArray[mid]);
if(compResult == 0)
return mid;
else if (compResult < 0)
return binarySearch(inputArray, searchKey, first, mid -1);
else
return binarySearch(inputArray, searchKey, mid + 1, last);
}
}
public static Object[] binarySearch(Object[] inputArray, int arraySize, Comparable searchKey) {
Object[] output = new Object[1];
int index = binarySearch(inputArray, searchKey, 0, arraySize -1);
if(index >= 0)
output[0] = inputArray[index];
return output;
}
}
Tweet.java
Tweet.java
public class Tweet implements Comparable