Exercise-2 a) Write a JAVA program to search for an element in a given list of elements
using binary search mechanism.
import [Link].*;
class Bin{
public static void binarySearch(int arr[], int low, int high, int key){
int mid = (low + high)/2;
[Link]("mid = " + mid);
while( low <= high )
{
if ( arr[mid] < key )
{
low = mid + 1;
}
else if ( arr[mid] == key ){
[Link]("Element is found at index: " + mid);
break;
}
else{
high = mid - 1;
}
mid = (low + high)/2;
}
if ( low > high ){
[Link]("Element is not found!");
}
}
public static void main(String args[])
{
int i,n,key;
Scanner sc =new Scanner([Link]);
[Link]("Enter the Number of Elements in Array : ");
n= [Link]();
int arr[]= new int[n];
[Link]("Enter the Elements of Array (Ascending Order): ");
for( i=0;i<n;i++)
{
arr[i]=[Link]();
}
[Link]("Enter the Number to be Searched : ");
key=[Link]();
int high=[Link]-1;
binarySearch(arr,0,high,key);
}
}
b) Write a JAVA program to sort for an element in a given list of elements using bubble sort.
import [Link];
class BubbleSort {
void bubbleSort(int arr[]) {
int n = [Link];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printArray(int arr[]) {
int n = [Link];
for (int i = 0; i < n; ++i) {
[Link](arr[i] + " ");
}
[Link]();
}
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
BubbleSort sorter = new BubbleSort();
[Link]("Enter the number of elements in the array:");
int n = [Link]();
int arr[] = new int[n];
[Link]("Enter the elements in the array:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
[Link](arr);
[Link]("Sorted array:");
[Link](arr);
[Link]();
}
}
c) Write a JAVA program using StringBuffer to delete ,remove character.
import [Link];
public class StringBuffer1 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
Scanner sc = new Scanner([Link]);
while (1) {
[Link]("Menu:\n" +
"1. Append text\t" +
"2. Insert text\t" +
"3. Replace text\t" +
"4. Delete text\t" +
"5. Remove character\t" +
"6. Display content\t" +
"7. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
[Link]();
switch (choice) {
case 1:
[Link]("World");
[Link]("Text appended.");
break;
case 2:
[Link](5, "Beautiful");
[Link]("Text inserted.");
break;
case 3:
[Link](5, 14, "Busy");
[Link]("Text replaced.");
break;
case 4:
[Link](5, 8);
[Link]("Text deleted.");
break;
case 5:
[Link](5);
[Link]("Character removed.");
break;
case 6:
[Link]("Current StringBuffer content: " + sb);
break;
case 7:
[Link](0);
default:
[Link]("Invalid option.");
break;
}
}
}
}