-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLearningPractice.java
More file actions
77 lines (66 loc) · 2.07 KB
/
Copy pathLearningPractice.java
File metadata and controls
77 lines (66 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public class LearningPractice {
public static int linearSearch(int arr[], int x) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == x) {
System.out.println("Element found at index: " + i);
return i;
}
}
return -1;
}
public static int getLargestValue(int arr[]) {
int largest = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
public static int binarySearch(int arr[], int i, int j, int x) {
int mid = (i + j) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
return binarySearch(arr, i, mid - 1, x);
} else {
return binarySearch(arr, mid + 1, j, x);
}
}
public static void reverseArray(int arr[]) {
int i = 0;
int j = arr.length - 1;
while (i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
public static void pairsInArray(int arr[]) {
for (int i = 0; i < arr.length; i++) {
int first = arr[i];
for (int j = i + 1; j < arr.length; j++) {
int second = arr[j];
System.out.println(first + " " + second);
}
System.out.println();
}
}
public static void main() {
int arr[] = {10, 20, 30, 40, 50};
int returnValue = linearSearch(arr, 10);
if (returnValue > -1) {
System.out.println("Element found at index: " + returnValue);
} else {
System.out.println("Element not found");
}
int largestValue = getLargestValue(arr);
System.out.println("Largest value: " + largestValue);
int searchIndex = binarySearch(arr, 0, arr.length - 1, 20);
System.out.println("Element found at index: " + searchIndex);
reverseArray(arr);
pairsInArray(arr);
}
}