रेफरेंस की स्थानीयता के आधार पर खोज करना, मेमोरी एक्सेस पैटर्न पर निर्भर करता है डेटा एलिमेंट्स को पुनः आवंटित किया जाता है।
यहां एलिमेंट खोजने के लिए लीनियर सर्चिंग मेथड का उपयोग किया जाता है।
एल्गोरिदम
Begin
int find(int *intarray, int n, int item)
comparisons = 0 इनिशियलाइज़ करें
for i = 0 to n-1
comparisons बढ़ाएं
if (item == intarray[i])
एलिमेंट को इसके इंडेक्स के साथ प्रिंट करें
break
if (i == n-1)
"element not found" प्रिंट करें
return -1
Total comparisons प्रिंट करें
For j = i till i > 0
intarray[j] = intarray[j-1]
intarray[0] = item
return 0
End
उदाहरण
#include <iostream>
using namespace std;
// लीनियर सर्च करने के लिए फंक्शन
// यह मेथड लीनियर सर्च करता है
int find(int *intarray, int n, int item) {
int i;
int comparisons = 0;
// सभी आइटम्स के माध्यम से नेविगेट करें
for (i = 0; i < n; i++) {
// की गई तुलनाओं की गिनती
comparisons++;
// यदि आइटम मिला, तो लूप तोड़ें
if (item == intarray[i]) {
cout << "element found at: " << i << endl;
break;
}
// यदि इंडेक्स अंत तक पहुंच गया तो आइटम वहां नहीं है
if (i == n-1) {
cout << "\nThe element not found.";
return -1;
}
}
printf("Total comparisons made: %d", comparisons);
// मिलान आइटम से पहले प्रत्येक एलिमेंट को शिफ्ट करें
for (int j = i; j > 0; j--)
intarray[j] = intarray[j-1];
// हाल ही में खोजे गए आइटम को डेटा ऐरे की शुरुआत में रखें
intarray[0] = item;
return 0;
}
int main() {
int intarray[20] = {1, 2, 3, 4, 6, 7, 9, 11, 12, 14, 15, 16, 26, 19, 33, 34, 43, 45, 55, 66};
int i, n;
char ch;
// प्रारंभिक डेटा ऐरे प्रिंट करें
cout << "\nThe array is: ";
for (i = 0; i < 20; i++)
cout << intarray[i] << " ";
up:
cout << "\nEnter the Element to be searched: ";
cin >> n;
// अपडेटेड डेटा ऐरे प्रिंट करें
if (find(intarray, 20, n) != -1) {
cout << "\nThe array after searching is: ";
for (i = 0; i < 20; i++)
cout << intarray[i] << " ";
}
cout << "\n\nWant to search more.......yes/no(y/n)? ";
cin >> ch;
if (ch == 'y' || ch == 'Y')
goto up;
return 0;
}
आउटपुट
The array is: 1 2 3 4 6 7 9 11 12 14 15 16 26 19 33 34 43 45 55 66 Enter the Element to be searched: 26 element found at: 12 Total comparisons made: 13 The array after searching is: 26 1 2 3 4 6 7 9 11 12 14 15 16 19 33 34 43 45 55 66 Want to search more.......yes/no(y/n)? y Enter the Element to be searched: 0 The element not found. Want to search more.......yes/no(y/n)? n