Java Algorithm Learning (search for numbers)

Source: Internet
Author: User

Search for numbers

Generate 20 integers at random and enter the data to be searched;

Compare data one by one. When the data is equal, locate the data and output the data location.

The Code is as follows:

Package com. Xu. Main;

Import java. util. Random;
Import java. util. collections;

Public class p1_1 {

/**
* @ Function: Search for numbers
* @ Author:
* @ Date: 2012-10-14
*/
Static int n = 20;

Public static void main (string [] ARGs ){
// Todo auto-generated method stub
Int [] arr = new int [20];
Int X, I;
Int F =-1;

Random r = new random ();
// Random Seed
For (I = 0; I <n; I ++)
// Generate a random number
{
Arr [I] = R. nextint (100 );
}

System. Out. println ("randomly generated data sequence :");
For (I = 0; I <n; I ++)
{
System. Out. Print (ARR [I] + "");
// Output sequence
}

System. Out. println ("\ n ");

System. Out. println ("Enter the integer to be searched :");
S = new partition (system. In );
X = S. nextint ();
// Enter the number to be searched

For (I = 0; I <n; I ++)
// Sequential search
{
If (x = arr [I])
// Locate the data
{
F = I;
Break;

}
}
If (F <0)
{
System. Out. println ("no data found:" + x );
}
Else
{
System. Out. println ("data:" + x + "in the array" + (F + 1) + "element .");
}
}

}

Running result:

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.