Tutorials Java Linear / Sequential Search Example in Java

Linear / Sequential Search Example in Java

Quick Java code snippet to show Linear / Sequential Search.

import java.util.Scanner;

public class LinearSearchExample {

	public static void main(String args[]) {
		int i, totalCount, search, inputArray[];

		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter number of elements");
		totalCount = scanner.nextInt();
		inputArray = new int[totalCount];

		System.out.println("Enter " + totalCount + " integers");

		for (i = 0; i < totalCount; i++) {
			inputArray[i] = scanner.nextInt();
		}

		System.out.println("Enter value to find");
		search = scanner.nextInt();

		for (i = 0; i < totalCount; i++) {
			// Element found
			if (inputArray[i] == search) {
				System.out.println(search + " is present at location "
						+ (i + 1) + ".");
				break;
			}
		}

		// Element not in the input array
		if (i == totalCount) {
			System.out.println(search + " is not present in array.");
		}
	}
}

Output

Linear : Sequential Search Example in Java

Total
0
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post
Wordpress Tutorials

Include Custom Post Types in Your WordPress RSS Feed

Next Post

ListView Header Parallax in Android

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
0
Would love your thoughts, please comment.x
()
x