使用二分搜尋法查詢陣列的最小元素的 C++ 程式


這是一個使用線性搜尋法查詢陣列最小元素的 C++ 程式。此程式的時間複雜度為 O(log(n))。

演算法

Begin
   Construct binary search tree for the given unsorted data array.
   To find out the minimum element move the pointer to the leftmost child node.
   Print this value as minimum value among the given data.
End

示例程式碼

#include<iostream>
using namespace std;
struct node {
   int d;
   node *left;
   node *right;
};
node* CreateNode(int d) {
   node *newnode = new node;
   newnode->d = d;
   newnode->left = NULL;
   newnode->right = NULL;
   return newnode;
}
node* InsertIntoTree(node* root, int d) {
   node *temp = CreateNode(d);
   node *t = new node;
   t = root;
   if(root == NULL)
      root = temp;
   else{
      while(t != NULL) {
         if(t->d < d) {
            if(t->right == NULL) {
               // If current node is NULL then insert the node.
               t->right = temp;
               break;
            }
            // Shift pointer to the left.
            t = t->right;
         }
         else if(t->d > d) {
            if(t->left == NULL) {
               t->left = temp;
               break;
            }
            t = t->left;
         }
      }
   }
   return root;
}
int main() {
   int n, i, a[10]={86, 63, 95, 6, 7, 67, 52, 26, 45, 98};
   node *root = new node;
   root = NULL;
   cout<<"\nData set:\n";
   for(i = 0; i < 10; i++) {
      cout<<a[i]<<" ";
      root = InsertIntoTree(root, a[i]);
   }
   cout<<"\n\nThe minimum element of the given data set is ";
   i = 0;
   while(root->left != NULL) {
      i++;
      root = root->left;
   }
   cout<<root->d<<" which found at "<<i<<" depth from the root.";
   return 0;
}

輸出

Data set:
86 63 95 6 7 67 52 26 45 98
The minimum element of the given data set is 6 which found at 2 depth from the root.

更新日期: 2019-07-30

195 次瀏覽

開啟你的 職業生涯

完成課程並獲取認證

開始學習
廣告