Java program for linear search an unsorted array?
Problem statement
Write a java program for linear search of an unsorted array. Run your program with a few testcases do demonstrate your program.
An unsorted or unordered array is an array where elements of the array are not sorted. To search for an element in this array, you have to scan the entire array to check if the element is present or not.
Flow Chart for linear search
Environment
Tools used to develop the program:
- JDK
- IntelliJ IDE
Java Program
import java.util.InputMismatchException; import java.util.Scanner; public class LinearSearch { public static void main(String[] args) { int n , index = -1; Scanner input = null; int[] a = null; try { input=new Scanner(System.in); System.out.println("Enter size of the array:"); n= input.nextInt(); if(n > 1) { a=new int[n]; System.out.println("Enter array elements:"); for (int i = 0; i < n; i++) { a[i] = input.nextInt(); } }else{ //quit System.exit(0); } System.out.println("Input Array:"); printArray(a); System.out.println("Enter the value to find:"); int search_item= input.nextInt(); for(int i=0;i<n;i++){ if(search_item==a[i]) { index = i; break; } } if(index == -1 ) { System.out.println("Search item not found in the array"); System.exit(0); } else{ System.out.println("Item found at position " + index +" marked with *:" ); printArray(a,index); } }catch (InputMismatchException ime) { System.out.println("Not a valid input"); } catch (Exception e) { e.printStackTrace(); } finally { if(input!=null) {input.close();} } } private static void printArray(int[] a){ for (int anA : a) { System.out.print("[ " + anA + " ]"); } System.out.println( ""); } private static void printArray(int[] a, int index){ for (int i=0;i< a.length;i++) { if(i == index) System.out.print("[* " + a[i] + "*]"); else System.out.print("[ " + a[i] + " ]"); } System.out.println( ""); } }
Run output
Save the program in the IDE. Execute the program and run the test cases.
Testcase
Enter size of the array:
7
Enter array elements:
23
56
89
99
156
1089
34
Input Array:
[ 23 ][ 56 ][ 89 ][ 99 ][ 156 ][ 1089 ][ 34 ]
Enter the value to find:
156
Item found at position 4 marked with *:
[ 23 ][ 56 ][ 89 ][ 99 ][* 156*][ 1089 ][ 34 ]
Testcase
Enter size of the array:
7
Enter array elements:
23
56
89
99
156
1089
34
Input Array:
[ 23 ][ 56 ][ 89 ][ 99 ][ 156 ][ 1089 ][ 34 ]
Enter the value to find:
1088
Search item not found in the array
Testcase
Enter size of the array:
-123
Enter positive number.
Testcase
Enter size of the array:
string
Not a valid input
—
Java Tutorial on this website: https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :