रैखिक खोज

इस ट्यूटोरियल में, आप रैखिक खोज के बारे में जानेंगे। इसके अलावा, आप रैखिक खोज सी, सी ++, जावा और पायथन के काम करने के उदाहरण पाएंगे।

रैखिक खोज सबसे सरल खोज एल्गोरिथ्म है जो अनुक्रमिक क्रम में एक सूची में एक तत्व की खोज करता है। हम एक छोर पर शुरू करते हैं और प्रत्येक तत्व की जांच करते हैं जब तक कि वांछित तत्व नहीं मिलता है।

रैखिक खोज कैसे काम करती है?

k = 1नीचे दी गई सूची में एक तत्व की खोज करने के लिए निम्नलिखित चरणों का पालन किया जाता है ।

खोजा जा रहा है
  1. पहले तत्व से शुरू करें, प्रत्येक तत्व x के साथ k की तुलना करें। प्रत्येक तत्व के साथ तुलना करें
  2. यदि x == k, इंडेक्स वापस करें। तत्व मिला
  3. और, नहीं मिला।

रैखिक खोज एल्गोरिथ्म

यदि आइटम == मान अपने इंडेक्स को लौटाता है, तो प्रत्येक आइटम के लिए रैखिक खोज (सरणी, कुंजी)

पायथन, जावा और सी / सी ++ उदाहरण

पायथन जावा सी सी ++
 # Linear Search in Python def linearSearch(array, n, x): # Going through array sequencially for i in range(0, n): if (array(i) == x): return i return -1 array = (2, 4, 0, 1, 9) x = 1 n = len(array) result = linearSearch(array, n, x) if(result == -1): print("Element not found") else: print("Element found at index: ", result)
 // Linear Search in Java class LinearSearch ( public static int linearSearch(int array(), int x) ( int n = array.length; // Going through array sequencially for (int i = 0; i < n; i++) ( if (array(i) == x) return i; ) return -1; ) public static void main(String args()) ( int array() = ( 2, 4, 0, 1, 9 ); int x = 1; int result = linearSearch(array, x); if (result == -1) System.out.print("Element not found"); else System.out.print("Element found at index: " + result); ) )
 // Linear Search in C #include int search(int array(), int n, int x) ( // Going through array sequencially for (int i = 0; i < n; i++) if (array(i) == x) return i; return -1; ) int main() ( int array() = (2, 4, 0, 1, 9); int x = 1; int n = sizeof(array) / sizeof(array(0)); int result = search(array, n, x); (result == -1) ? printf("Element not found") : printf("Element found at index: %d", result); )
 // Linear Search in C++ #include using namespace std; int search(int array(), int n, int x) ( // Going through array sequencially for (int i = 0; i < n; i++) if (array(i) == x) return i; return -1; ) int main() ( int array() = (2, 4, 0, 1, 9); int x = 1; int n = sizeof(array) / sizeof(array(0)); int result = search(array, n, x); (result == -1) ? cout << "Element not found" : cout << "Element found at index: " << result; )

रेखीय खोज जटिलताएँ

समय जटिलता: O (n)

अंतरिक्ष जटिलता: O(1)

रैखिक खोज अनुप्रयोग

  1. छोटे सरणियों (<100 आइटम) में खोज अभियान के लिए।

दिलचस्प लेख...