Macky110495
Enthusiast
- Joined
- Nov 8, 2020
- Posts
- 1
- Reaction
- 0
- Points
- 32
SELECTION SORT: For Girls
public class SelectionSort {
public static void selectionSort(int[] arr){
// Write a java program to sort the array elements in ascending order
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;
}
}
int smallerNumber = arr[index];
arr[index] = arr;
arr = smallerNumber;
}
}
public static void main(String[] args) {
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
} }
BINARY SEARCH: For Girls
public class BinarySearch {
int binarySearch(int array[], int x, int low, int high) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
public static void main(String[] args) {
BinarySearch ob = new BinarySearch();
int array[] = { 3, 4, 5, 6, 7, 8, 9 };
int n = array.length;
int x = 1;
int result = ob.binarySearch(array, x, 0, n - 1);
if (result == -1)
System.out.println("Not found");
else
System.out.println("Element found at index " + result);
}
}
public class SelectionSort {
public static void selectionSort(int[] arr){
// Write a java program to sort the array elements in ascending order
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;
}
}
int smallerNumber = arr[index];
arr[index] = arr;
arr = smallerNumber;
}
}
public static void main(String[] args) {
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
} }
BINARY SEARCH: For Girls
public class BinarySearch {
int binarySearch(int array[], int x, int low, int high) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
public static void main(String[] args) {
BinarySearch ob = new BinarySearch();
int array[] = { 3, 4, 5, 6, 7, 8, 9 };
int n = array.length;
int x = 1;
int result = ob.binarySearch(array, x, 0, n - 1);
if (result == -1)
System.out.println("Not found");
else
System.out.println("Element found at index " + result);
}
}