C程式語言提供了兩種搜尋技術。它們如下所示:
在這裡,可能會發生三種情況,如下所示:
#如果中間元素與關鍵字匹配,則搜尋將在此成功結束
如果中間元素大於關鍵字,則搜尋將在左側分區進行。
如果中間元素小於關鍵字,則搜尋將在右側分區進行。
輸入 (i/p) - 未排序的元素列表,關鍵字。
輸出(o/p) -
key = 20 mid = (low +high) /2
以下是使用二分尋找在陣列中找到最小元素的C程式:
#include<stdio.h> int main(){ int a[50], n, i, key, flag = 0, low, mid, high; printf("enter the no: of elements:"); scanf ("%d",&n); printf("enter the elements:"); for(i=0; i<n; i++) scanf( "%d", &a[i]); printf("enter a key element:"); scanf ("%d", &key); low = 0; high = n-1; while (low<= high ){ mid = (low + high) /2; if (a[mid] == key){ flag = 1; break; } else{ if (a[mid] > key) high = mid-1; else low = mid+1; } } if (flag == 1) printf ("search is successful"); else printf("search is unsuccessful"); return 0; }
當上述程式被執行時,它產生以下結果−
Run 1: enter the no: of elements:5 enter the elements: 12 34 11 56 67 enter a key element:45 search is unsuccessful Run 2: enter the no: of elements:3 enter the elements: 12 34 56 enter a key element:34 search is successful
給定下面的C程序,透過使用二分查找來找到陣列中的最小元素−
#include<stdio.h> void Bmin(int *a, int i, int n){ int j, temp; temp = a[i]; j = 2 * i; while (j <= n){ if (j < n && a[j+1] > a[j]) j = j + 1; if (temp < a[j]) break; else if (temp >= a[j]){ a[j / 2] = a[j]; j = 2 * j; } } a[j/2] = temp; return; } int binarysearchmin(int *a,int n){ int i; for(i = n/2; i >= 1; i--){ Bmin(a,i,n); } return a[1]; } int main(){ int n, i, x, min; int a[20]; printf("Enter no of elements in an array</p><p>"); scanf("%d", &n); printf("</p><p>Enter %d elements: ", n); for (i = 1; i <= n; i++){ scanf("%d", &a[i]); } min = binarysearchmin(a, n); printf("\minimum element in an array is : %d", min); return 0; }
當上述程式被執行時,它產生下列結果−
Enter no of elements in an array 5 Enter 5 elements: 12 23 34 45 56 minimum element in an array is: 12
以上是如何使用二分查找演算法在C語言中找到數組中的最小元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!