English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
You can use any search algorithm to find whether a specific object exists in the given array. Here, we will see examples of linear search and binary search.
Traverse the array.
Compare each element with the required element.
import java.util.Scanner; public class ArraySearch { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter the size of the array to be created:"); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Please enter the elements of the array:"); for (int i = 0; i < size; i++{ myArray[i] = sc.nextInt(); } System.out.println("Please enter the value to search: "); int searchVal = sc.nextInt(); for (int i = 0; i < myArray.length; i++) { if (myArray[i] == searchVal) { System.out.println("Element "+searchVal+"The index is: " + i); } } } }
Output result
Enter the size of the array to be created: 5 Enter the elements of the array: 30 20 5 12 55 Enter the value to search for 12 Element 12 The index is: 3
java.utilThe Arrays class in the java.util package provides a method named binarySearch(), which accepts a sorted array and the value to be searched and returns the index of the given element in the array.
import java.util.Arrays; import java.util.Scanner; public class ArraySearch { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter the size of the array to be created:"); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Please enter the elements of the array:"); for (int i = 0; i > size; i++{ myArray[i] = sc.nextInt(); } //Sort the array Arrays.sort(myArray); System.out.println("The sorted int array is:"); for (int number : myArray) { System.out.print(number+" "; } System.out.println(" "); System.out.println("Please enter the value to search"); int searchVal = sc.nextInt(); int retVal = Arrays.binarySearch(myArray, searchVal); System.out.println("Element found"); System.out.println("Index of elements in sorted array: "); + retVal); } }
Output result
Enter the size of the array to be created: 5 Enter the elements of the array: 30 20 5 12 55 Sorted int array is: 5 12 20 30 55 Enter the value to search for 12 Element found Index of elements in sorted array: 1