axsoft
版主
發表:681 回覆:1056 積分:969 註冊:2002-03-13
發送簡訊給我
|
連續搜尋法(Sequential Search) /* Sequential Search
Written by: F & G
Date: 2/98
Revised 5/98 Converted to C++ Copyright 2001
Brooks/Cole Publishing
Thomson Learning
All Rights Reserved
*/
#include
#include
#include // Constants
const int SIZE = 100; // Prototype Declarations
bool seqSearch (int list[ ], int end, int target, int& locn); int main (void)
{
// Local Declarations
int i;
int list[SIZE];
int srchArgu;
int foundLocn; // Statements
cout << "Demonstrate Sequential Search\n"; // Fill Array
srand(997);
for (i = 0; i < SIZE; i )
list[i] = rand() % 500; cout << "You may search the following array: \n" ;
for (i = 0; i < SIZE; i )
{
if (!(i % 10))
cout << endl;;
cout << setw (4) << list[i];
} // for
cout << endl ; cout << "\nEnter a number in the list: ";
cin >> srchArgu ;
i = seqSearch (list, SIZE - 1, srchArgu, foundLocn);
if (i)
cout << "Found " << list[foundLocn] << " @ index location "
<< foundLocn << endl;
else
cout << "Did not find " << srchArgu ; cout << "\nEnter a number not in the list: ";
cin >> srchArgu ;
i = seqSearch (list, SIZE - 1, srchArgu, foundLocn);
if (i)
cout << "Found " << list[foundLocn] << " @ index location "
<< foundLocn << endl;
else
cout << "Did not find " << srchArgu << endl; return 0;
} // main /* Locate the target in an unordered list of size elements.
Pre: list must contain at least one item.
last is index to last element in the list
target contains the data to be located
locn is address to index in calling function
Post: FOUND: matching index stored at locn
return true (found)
NOT FOUND: last stored in locn address.
return false (not found)
*/
bool seqSearch (int list[],
int last,
int target,
int& locn)
{
// Local Definitions
int looker; // Statements
looker = 0;
while (looker < last && target != list[looker])
looker ; locn = looker;
return (target == list[looker]);
} // seqSearch /* Results--Note: You will get different numbers Demonstrate Sequential Search
You may search the following array: 75 303 276 437 36 361 157 79 179 126
10 407 463 334 378 182 197 411 330 254
107 377 295 61 48 486 201 43 99 420
309 321 457 374 433 391 201 173 420 382
33 399 234 274 309 110 246 226 258 245
169 263 304 16 305 22 369 261 488 364
97 478 347 446 387 202 435 264 13 77
103 459 43 271 340 86 377 420 31 363
72 441 272 370 246 103 71 381 365 336
179 133 374 322 462 331 195 55 342 4 Enter a number in the list: 4
Found 4 @ index location 99 Enter a number not in the list: -15
Did not find -15
*/ 網路志工聯盟----Visita網站http://www.vista.org.tw
---[ 發問前請先找找舊文章 ]---
|