Docsity

Sequential and Binary Search Algorithms in C++, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
NURSYAZA NISA BINTI ARFARIZAL
B032010244
BITP 1123
SECTION 1
GROUP 1
PROGRAM 4.3.1 (SEQUENTIAL SEARCH)
// Sequential.h
#ifndef SEQUENTIAL_H
#define SEQUENTIAL_H
const int SIZE = 10;
class Sequential
{
public:
int locationWanted;
int array[SIZE];
bool SequentialSearch(int[], int, int, int&);
};
#endif
// Sequential.cpp
#include <iostream>
using namespace std;
#include "Sequential.h"
bool Sequential::SequentialSearch(int array[], int SIZE,
int target, int& locWanted)
{
int index = 0;
bool found = false;
while (index < SIZE - 1)
{
if (array[index] != target)
index++;
else
{
found = true;
locWanted = index;
break;
}
}
return found;
}
// Utama.cpp
using namespace std;
#include "Sequential.h"
void main()
{
int target, i;
bool found;
Sequential SS;
pf3
pf4

Partial preview of the text

Download Sequential and Binary Search Algorithms in C++ and more Study notes Data Structures and Algorithms in PDF only on Docsity!

NURSYAZA NISA BINTI ARFARIZAL

B

BITP 1123

SECTION 1

GROUP 1

PROGRAM 4.3.1 (SEQUENTIAL SEARCH)

// Sequential.h #ifndef SEQUENTIAL_H #define SEQUENTIAL_H const int SIZE = 10; class Sequential { public: int locationWanted; int array[SIZE]; bool SequentialSearch(int[], int, int, int&); }; #endif // Sequential.cpp #include using namespace std; #include "Sequential.h" bool Sequential::SequentialSearch(int array[], int SIZE, int target, int& locWanted) { int index = 0; bool found = false; while (index < SIZE - 1) { if (array[index] != target) index++; else { found = true; locWanted = index; break; } } return found; } // Utama.cpp using namespace std; #include "Sequential.h" void main() { int target, i; bool found; Sequential SS;

cout << "The Data\n"; for (i = 0; i < SIZE; i++) SS.array[i] = rand() % 500 + 1; for (i = 0; i < SIZE; i++) cout << SS.array[i] << " "; cout << endl; cout << "Insert a target, or 0 to stop: "; cin >> target; do { found = SS.SequentialSearch(SS.array, SIZE, target, SS.locationWanted); if (found) cout << "\tFound " << target << " at index " << SS.locationWanted << endl; else cout << "\tTarget not found" << endl; cout << "\nInsert a target, or 0 to stop: "; cin >> target; } while (target != 0); } OUTPUT:

bool found; Binary BS; cout << "The Data\n"; /generate an ordered random number list/ BS.array[0] = 1; no = rand() % 500 + 1; while (i < SIZE) { if (no >= BS.array[i - 1]) { BS.array[i] = no; i++; } no = rand() % 500 + 1; } for (i = 0; i < SIZE; i++) cout << BS.array[i] << " "; cout << endl; cout << "Insert a target, or 0 to stop: "; cin >> target; do { found = BS.BinarySearch(BS.array, SIZE, target, BS.locationWanted); if (found) cout << "\n\tFound " << target << " at index " << BS.locationWanted << endl; else cout << "\n\tTarget not found" << endl; cout << "\nInsert a target, or 0 to stop: "; cin >> target; } while (target != 0); } OUTPUT: