please tell me the answers of these programs.
Answers
Answer:
1.
Code
-------------------------------------------------------------
import java.util.Scanner;
public class BubbleSort {
public static int sumOfDigits(int number) {
int sumOfDigits = 0;
while (number > 0) {
sumOfDigits = sumOfDigits + number%10;
number = number / 10;
}
return sumOfDigits;
}
public static void bubbleSort(int[] integerArray,int totalNo) {
int i, j, temp;
boolean swapped;
for (i = 0; i < totalNo - 1; i++) {
swapped = false;
for (j = 0; j < totalNo - i - 1; j++) {
if (integerArray[j] < integerArray[j + 1]) {
temp = integerArray[j];
integerArray[j] = integerArray[j + 1];
integerArray[j + 1] = temp;
swapped = true;
}
}
if (!swapped)
break;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the 5 numbers");
int totalNo = 5;
int[] integerArray = new int[totalNo];
for (int index = 0;index < totalNo;index++) {
integerArray[index] = scanner.nextInt();
}
bubbleSort(integerArray, totalNo);
for (int index = 0;index < totalNo;index++) {
System.out.println(sumOfDigits(integerArray[index]));
}
}
}
-------------------------------------------------------------
Output
Enter the 5 numbers
10 20 40 50 100
1
5
4
2
1
-------------------------------------------------------------
2.
Code
-------------------------------------------------------------
import java.util.Arrays;
import java.util.Scanner;
public class BubbleSort {
public static Integer binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return null;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the 10 numbers");
int totalNo = 10;
int[] integerArray = new int[totalNo];
for (int index = 0;index < totalNo;index++) {
integerArray[index] = scanner.nextInt();
}
Arrays.sort(integerArray);
System.out.println("Enter the number to search");
int searchNumber = scanner.nextInt();
if (binarySearch(integerArray, 0, totalNo - 1, searchNumber) != null) {
System.out.println("Search Successfull");
} else {
System.out.println("Search Unsuccessfull");
}
}
}
-------------------------------------------------------------
Output
Enter the 10 numbers
10 20 30 40 50 60 70 80 90 100
Enter the number to search
10
Search Successfull
-------------------------------------------------------------