Getting Started with Java: A linear search of basic algorithms

Source: Internet
Author: User

This program uses a linear search algorithm to find a number from the N number.

/*Program : Linear Search Example * @author: Tech Cloud Classroom * Input: Number of elements, value per element, value to find data * Output: Location of number to find*/ImportJava.util.Scanner;classlinearsearchexample{ Public Static voidMain (String args[]) {intcounter, num, item, array[]; //capturing user inputScanner input =NewScanner (system.in); System.out.println ("Enter Number of elements:"); Num=Input.nextint (); //create an array to hold all integersArray =New int[num];
System.out.println (
"Enter" + num + "integers"); //loop to store the number of user input in an array for(counter = 0; counter < num; counter++) Array[counter]=Input.nextint (); System.out.println ("Enter The Search value:"); Item=Input.nextint (); for(counter = 0; counter < num; counter++) { if(Array[counter] = =Item) {SYSTEM.OUT.PRINTLN (item+ "is present @ location" + (counter+1)); / * Find this number to stop the lookup and use break to terminate the For loop. */ Break; } } if(Counter = =num) SYSTEM.OUT.PRINTLN (Item+ "doesn ' t exist in array."); }}

Output 1:

Enter Number of elements:66 integers2233451399Enter The search value:4545 is Present at location 3

Output 2:

Enter Number of elements: 4  4  integers45Enter The search value:  About  doesn't exist in array.

Getting Started with Java: A linear search of basic algorithms

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.