import java.io.*;
class GFG {
public static int search(int arr[], int N, int x) {
for (int i = 0; i < N; i++) {
if (arr[i] == x)
return i; }
return -1; }
public static void main(String args[]) {
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int result = search(arr, arr.length, x);
if (result == -1)
System.out.print(
"Element is not present in array");
else
System.out.print("Element is present at index "
+ result); }}
public class Main {
public static void main(String[] args) {
int[] myArray = {1,3,5,7,9,11,13,15,17,19};
int myTarget = 15;
int result = binarySearch(myArray, myTarget);
if (result != -1) {
System.out.println("Value " + myTarget + " found at index " + result);
} else {
System.out.println("Target not found in array.");}}
public static int binarySearch(int[] arr, int targetVal) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == targetVal) {
return mid; }
if (arr[mid] < targetVal) {
left = mid + 1;
} else {
right = mid - 1; }
}
return -1; }
}
Sequential Search vs Binary Search
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
static void selectionSort(int[] arr){
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
// Assume the current position holds the minimum element
int min_idx = i;
// Iterate through the unsorted portion to find the actual minimum
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller element is found
min_idx = j; } }
// Move minimum element to its correct position
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp; }}
public class Main {
public static void main(String[] args) {
int[] my_array = {64,34,25,12,22,11,90,5};
int n = my_array.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (my_array[j] > my_array[j+1]) {
int temp = my_array[j];
my_array[j] = my_array[j+1];
my_array[j+1] = temp;
}}}
System.out.print("Sorted array: ");
for (int i = 0; i < n; i++) {
System.out.print(my_array[i] + " ");}
System.out.println();}}
//Use recursion to add all of the numbers up to 10.
public class Main {
public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}
If you wish to learn swimming you have to go into the water and if you wish to become a problem solver you have to solve problems. (George Polya)