-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchingInAnUnsortedArray.java
More file actions
54 lines (43 loc) · 1.35 KB
/
Copy pathSearchingInAnUnsortedArray.java
File metadata and controls
54 lines (43 loc) · 1.35 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
/*
* Author: Hasnain Memon
* Date: 29/10/2024
*/
// Task : Search an element in an unsorted array
public class SearchingInAnUnsortedArray {
//This method returns index of element found.
static int findElement(int[] arr, int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
//This method returns boolean to confirm that element is present or not.
// static boolean findElement(int[] arr, int n, int key) {
//
// for (int i = 0; i < n; i++) {
// if (arr[i] == key) {
// return true;
// }
// }
//
// return false;
// }
public static void main(String[] args) {
int[] arr = {5, 1, 3, 10, 2, 6, 4};
int element = 4;
int index = findElement(arr, arr.length, element);
if (index == -1) {
System.out.println("Element not found!");
} else {
System.out.println("Element found at index " + index);
}
// boolean contains = findElement(arr, arr.length, element);
// if (!contains) {
// System.out.println("Element not found!");
// } else {
// System.out.println("This array contains element " + element);
// }
}
}