Untitled
unknown
plain_text
3 years ago
934 B
19
Indexable
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// funkcja przeszukiwania liniowego
int linearSearch(int arr[], int n, int x)
{
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i; // zwraca pozycję elementu w tablicy
}
}
return n; // zwraca wartość "n", jeśli elementu nie ma w tablicy
}
int main()
{
const int SIZE = 16;
int arr[SIZE] = { 7, 3, 5, 9, 1, 8, 2, 6, 4, 10, 15, 12, 13, 14, 11, 16 };
int x;
// generowanie losowej liczby z przedziału 1-16
srand(time(0));
x = rand() % 16 + 1;
cout << "Losowa liczba: " << x << endl;
int pos = linearSearch(arr, SIZE, x);
if (pos < SIZE) {
cout << "Element " << x << " znajduje się w tablicy na pozycji " << pos << endl;
}
else {
cout << "Element " << x << " nie znajduje się w tablicy." << endl;
}
return 0;
}Editor is loading...