JAVA I\'m asking for question 3, just posted question 2 as it is mentioned in qu
ID: 3585729 • Letter: J
Question
JAVA I'm asking for question 3, just posted question 2 as it is mentioned in question 3 Question 2 Given an unsorted array of N positive integer numbers sort them by implementing the bubble sort algorithm. Question 3 Given an array of N elements and an integer n, find the value of n and its position and print them to the console by implementing the binary search algorithm. Hint: binary search operates only on sorted arrays, thus you will need to utilize the solution of Question 2 to solve Question 3.
Explanation / Answer
public class Main
{
// Bubble Sort Implementation
public static void bubbleSort(int input_arr[])
{
int length_input = input_arr.length;
for (int i = 0; i < length_input-1; i++)
for (int j = 0; j < length_input-i-1; j++)
if (input_arr[j] > input_arr[j+1])
{
// swap temp and arr[i]
int temp = input_arr[j];
input_arr[j] = input_arr[j+1];
input_arr[j+1] = temp;
}
}
// Returns the index of num if it is present in input_arr[]
//else return -1
public static int binarySearch(int input_arr[], int num)
{
int start = 0, end = input_arr.length - 1;
while (start <= end)
{
int middle = start + (end-start)/2;
// Check if num is present at middle
if (input_arr[middle] == num)
return middle;
// If num greater, ignore left half of array
if (input_arr[middle] < num)
start = middle + 1;
// If num is smaller, ignore right half of array
else
end = middle - 1;
}
// if we reach here, then element was not present
return -1;
}
//Testing the above functions
public static void main(String args[])
{
int input_arr[] = {9,5,6,3,26,5};
int length_input = input_arr.length;
//works only on sorted array so first sort the given array
bubbleSort(input_arr);
//sorted Array : { 3 ,5 ,5 ,6 ,9 ,26 }
int num_to_find = 9;
int ans = binarySearch(input_arr, num_to_find);
if (ans == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element is found at index "+ans);
}
}
Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.