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

C++での単一リンクリストの二分探索


単一リンクリスト はリンクリスト(ノードの値と次のノードのメモリ位置を格納するデータ構造)であり、一方向にしか移動できません。

二分探索 分割統治に基づく検索アルゴリズムです。これにより、構造の中央の要素が検出され、不等式について同じアルゴリズムへの再帰呼び出しが比較および使用されます。

ここでは、単一リンクリストと、二分探索を使用して検出される要素が示されています。

単一リンクリストは1つのポインタのみを使用するデータ構造であるため、その中間要素を見つけるのは簡単ではありません。単一リンクリストの真ん中には、2つのポインターアプローチを使用します。

アルゴリズム

Step 1 : Initialize, start_node (head of list) and last_node (will have last value) , mid_node (middle node of the structure).
Step 2 : Compare mid_node to element
   Step 2.1 : if mid_node = element, return value “found”.
   Step 2.2 : if mid_node > element, call binary search on lower_Half.
   Step 2.3 : if mid_node < element, call binary search on upper_Half.
Step 3 : if entire list is traversed, return “Not found”.

#include<stdio.h>
#include<stdlib.h>
struct Node{
   int data;
   struct Node* next;
};
Node *newNode(int x){
   struct Node* temp = new Node;
   temp->data = x;
   temp->next = NULL;
   return temp;
}
struct Node* mid_node(Node* start, Node* last){
   if (start == NULL)
      return NULL;
   struct Node* slow = start;
   struct Node* fast = start -> next;
   while (fast != last){
      fast = fast -> next;
      if (fast != last){
         slow = slow -> next;
         fast = fast -> next;
      }
   }
   return slow;
}
struct Node* binarySearch(Node *head, int value){
   struct Node* start = head;
   struct Node* last = NULL;
   do{
      Node* mid = mid_node(start, last);
      if (mid == NULL)
         return NULL;
      if (mid -> data == value)
         return mid;
      else if (mid -> data < value)
         start = mid -> next;
      else
         last = mid;
   }
   while (last == NULL || last != start);
      return NULL;
}
int main(){
   Node *head = newNode(54);
   head->next = newNode(12);
   head->next->next = newNode(18);
   head->next->next->next = newNode(23);
   head->next->next->next->next = newNode(52);
   head->next->next->next->next->next = newNode(76);
   int value = 52;
   if (binarySearch(head, value) == NULL)
      printf("Value is not present in linked list\n");
   else
      printf("The value is present in linked list\n");
   return 0;
}

出力

The value is present in linked list

  1. C++の二分探索木イテレータ

    二分木用に1つのイテレータを作成するとします。 2つの方法があります。 next()メソッドは次の要素を返し、hasNext()メソッドはブール値を返します。これは次の要素が存在するかどうかを示します。したがって、ツリーが次のような場合- そして、関数呼び出しのシーケンスは、[next()、next()、hasNext()、next()、hasNext()、next()、hasNext()、next()、hasNext()]です。出力は[3,7、true、9、true、15、true、20、false]になります これを解決するには、次の手順に従います- nextとhasNextの

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

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