Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

SOLUTION IN JAVA PLEASE City. java File: Overview This lab has one activity that

ID: 3606237 • Letter: S

Question

SOLUTION IN JAVA PLEASE

City. java File:

Overview This lab has one activity that relates to searching a sorted array of cities using a binary search. To complete this lab you will need to download the required Lab 6 resources City.java Instructions Binary Search (10 marks) The only activity this week involves writing a binary search method (in a class called BinarySearch) that searches for a city by name and returns the City object if found. Create a sample try with two cities from each Canadian province What needs to be submitted? Please submit the following Java source files on Blackboard: City.java BinarySearch.java

Explanation / Answer

Please find below code:

import java.util.Arrays;

public class BinarySearch

{

public static City binarySearch(City cities[], int start, int end, City city)

{

if (end >= start)

{

int mid = start + (end - start)/2;

// If the element is present at the middle itself

if (cities[mid].compareTo(city) == 0)

return cities[mid];

// If element is smaller than mid, then it can only

// be present in left subarray

if (cities[mid].compareTo(city) > 0)

return binarySearch(cities, start, mid-1, city);

// Else the element can only be present in right

// subarray

return binarySearch(cities, mid+1, end, city);

}

// We reach here when element is not present in array

return null;

}

public static void main(String[] args){

City cities[] = new City[14];

cities[0] = new City("Victoria","British Columbia",100000);

cities[1] = new City("Fort Nelson","British Columbia",100000);

cities[2] = new City("Edmonton","Alberta",100000);

cities[3] = new City("Calgary","Alberta",100000);

cities[4] = new City("Regina","Saskatchewan",100000);

cities[5] = new City("Saskatoon","Saskatchewan",100000);

cities[6] = new City("Morden","Manitoba",100000);

cities[7] = new City("Winnipeg","Manitoba",100000);

cities[8] = new City("Emo","Ontario",100000);

cities[9] = new City("Toronto","Ontario",100000);

cities[10] = new City("Quebec City","Quebec",100000);

cities[11] = new City("Montreal","Quebec",100000);

cities[12] = new City("Fredericton","New Brunswick",100000);

cities[13] = new City("Moncton","New Brunswick",100000);

Arrays.sort(cities);

System.out.println("City Array After Sorting");

for(int i=0;i<13;i++){

System.out.println(cities[i]);

}

City city_search = binarySearch(cities, 0 , 13, cities[11]);

if(city_search != null)

System.out.println("City found -->" + city_search.getName());

else

System.out.println("City not found");

}

}