Write a Java driven application that performs the following tasks:
1. Allow the user to decide on the length of an array that will be created at run time.
2. Enter integer elements into such an array
3. Sort the elements in ascending order (DO NOT USE bubble sort)
4. Search for a user specified element in the array and return the number of times
the searched key is observed (DO NOT USE linear search)
import java.util.Arrays;
import java.util.Scanner;
public class Answer {
static void InsertionSort(int[] array){
for (int left = 0; left < array.length; left++) {
int value = array[left];
int i = left - 1;
for (; i >= 0; i--) {
if (value < array[i]) {
array[i + 1] = array[i];
} else {
break;
}
}
array[i + 1] = value;
}
}
static int binarySearch(int arr[], int elementToSearch) {
int firstIndex = 0;
int lastIndex = arr.length - 1;
int answer = 0;
while(firstIndex <= lastIndex) {
int middleIndex = (firstIndex + lastIndex) / 2;
if (arr[middleIndex] == elementToSearch) {
answer++;
if (arr[middleIndex] == arr[middleIndex - 1]) {
int mid = middleIndex;
while (arr[mid - 1] == elementToSearch) {
answer++;
mid--;
}
}
if (arr[middleIndex] == arr[middleIndex + 1]) {
int mid = middleIndex;
while (arr[mid + 1] == elementToSearch) {
answer++;
mid++;
}
}
return answer;
}
else if (arr[middleIndex] < elementToSearch)
firstIndex = middleIndex + 1;
else if (arr[middleIndex] > elementToSearch)
lastIndex = middleIndex - 1;
}
return -1;
}
public static void main(String[] args) {
System.out.println("Enter length of an array: ");
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
System.out.println("Enter array elements: ");
for (int i = 0; i < array.length; i++) {
array[i] =scanner.nextInt();
}
InsertionSort(array);
System.out.println("The array is sorted: ");
System.out.println(Arrays.toString(array));
System.out.println("Enter the element to find:");
int a = scanner.nextInt();
int ans = binarySearch(array, a);
if (ans == -1) {
System.out.println("There is no such element");
} else {
System.out.println("Matches: " + ans);
}
}
}
Comments
Leave a comment