C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

特定の検索シーケンスのバイナリ検索アルゴリズムを実装するC++プログラム


このプログラムでは、配列内の検索シーケンスの存在を見つけるために二分探索を実装する必要があります。二分探索の時間計算量はO(log(n))です。

必要な手順と擬似コード

Begin
   BinarySearch() function has ‘arr’ the array of data and ‘n’ the number of values, start and end index, iteration count and b[0] be the element to be searched in the argument list.
   Increment the iteration counter and compare the item value with the a[mid].
   If item < a[mid] choose first half otherwise second half to proceed further.
   Return index value to main.
   In main(), sequentially compare the remaining items of search sequence to next items in the array.
   Print the index range of the sequence found.
End.

サンプルコード

#include<iostream>
using namespace std;
int BinarySearch(int a[], int start, int end, int item, int iter) {
   int i, mid;
   iter++;
   mid = start+ (end-start+1)/2;
   if(item > a[end] || item < a[start] || mid == end) {
      cout<<"\nNot found";
      return -1;
   } else if(item == a[mid]) {
      return mid;
   } else if(item == a[start]) {
      return start;
   } else if(item == a[end]) {
      return end;
   } else if(item > a[mid])
      BinarySearch(a, mid, end, item, iter);
      else
         BinarySearch(a, start, mid, item, iter);
   }
int main() {
   int n, i, flag=0, Bin, len = 9, a[10]={1, 7, 15, 26, 29, 35, 38, 40, 49, 51};
   cout<<"\nEnter the number of element in the search sequence: ";
   cin>>n;
   int b[n];
   for(i = 0; i < n; i++) {
      cin>>b[i];
   }
   Bin = BinarySearch(a, 0, len, b[0], 0);
   if (Bin == -1) {
      cout<<"\nNot found.";
      return 0;
   } else {
      for(i = Bin; i < n+Bin; i++)
         if(a[i] != b[i-Bin])
            flag = 4;
            if(flag == 4)
               cout<<"\nNot found.";
            else
               cout<<"\nSequence found between index "<<Bin<<" and "<<Bin+n<<".";
   }
   return 0;
}

出力

Enter the number of element in the search sequence: 4
15
26
29
35
Sequence found between index 2 and 6.

  1. C ++プログラムでの二分探索?

    二分探索は、半区間探索、対数探索、または二分探索とも呼ばれ、ソートされた配列内のターゲット値の位置を見つける検索アルゴリズムです。二分探索は、ターゲット値を配列の中央の要素と比較します。それらが等しくない場合、ターゲットが存在できない半分が削除され、残りの半分で検索が続行され、再び中央の要素がターゲット値と比較され、ターゲット値が見つかるまでこれが繰り返されます。残りの半分が空の状態で検索が終了した場合、ターゲットは配列に含まれていません。アイデアは単純ですが、バイナリ検索を正しく実装するには、特に配列の値が範囲内の整数のすべてではない場合、終了条件と中間点の計算に関する微妙な点に注意する必要

  2. 配列シャッフリング用のFisher-Yatesアルゴリズムを実装するC++プログラム

    Fisher-Yatesアルゴリズムは、配列要素のランダムな順列を生成します。つまり、配列のすべての要素をランダムにシャッフルします。フィッシャー-イェーツアルゴリズムは偏りがないため、配列のすべての順列は同じように発生する可能性があります。 C++で配列シャッフルするためのFisher-Yatesアルゴリズムを実装するプログラムは次のとおりです- 例 #include <iostream> #include <t;stdlib.h> using namespace std; int main() {    int n;