二分查詢和排序
阿新 • • 發佈:2018-12-18
二分查詢,主要是針對排序問題進行查詢
我們先算出陣列的長度
len = sizeof(a) / sizeof(a[0])
我們先設定
int left = 0;
int right = Len - 1;
int mid = (left + right ) / 2;
如果K大於mid,那麼 left = mid + 1;
小於 right = mid -1;
#include <stdio.h> int search( int key, int a[], int len ) { int k; //scanf("%d", &k ); k = 99; int left = 0; int right = len - 1; int ret = -1; while ( right >= left ) { int mid = ( left + right ) / 2; if ( a[mid] == k ) { ret = mid; break; } else if ( a[mid] > k ) { right = mid - 1; } else { left = mid + 1; } } return ret; } int main() { int a[] = {1,3,5,7,8,9,11,34,56,65,67,88,99}; int len = sizeof(a) / sizeof(a[0]); int respond = 0; respond = search( 7, a, len ); printf("%d\n",respond); return 0; }
那麼如果我們碰到不是按順序排列的陣列,如何辦呢?
我們可以先排序然後再進行二分查詢
找到最大的數,然後和最後一個數進行swap,重複進行就行了。
#include <stdio.h> int max( int a[], int len ) { int maxid = 0; for ( int i = 1; i < len; i++ ) { if ( a[i] > a[maxid] ) { maxid = i; } } return maxid; } int main() { int a[] = {2,45,6,8,7,23,67,98,24,65,11,22,32}; int len = sizeof(a)/sizeof(a[0]); for ( int i = len - 1; i > 0; i-- ) { int maxid = max( a, i + 1 ); //swap a[maxid, a[len - 1] int t = a[maxid]; a[maxid] = a[i]; a[i] = t; } for ( int i = 0; i < len; i++ ) { printf("%d ", a[i]); } printf("\n"); return 0; }
完整的程式碼為
#include <stdio.h> int max( int a[], int len ) { int maxid = 0; for ( int i = 1; i < len; i++ ) { if ( a[i] > a[maxid] ) { maxid = i; } } return maxid; } int search( int key, int a[], int len ) { int k; scanf("%d", &k); int left = 0; int right = len - 1; int ret = -1; while ( right >= left ) { int mid = ( left + right ) / 2; if ( a[mid] == k ) { ret = mid; break; } else if ( a[mid] > k ) { right = mid - 1; } else { left = mid + 1; } } return ret; } int main() { int a[] = {1,2,3,4,5,66,54,22,43,78,21,23,24,42}; int len = sizeof(a) / sizeof(a[0]); for ( int i = len - 1; i > 0; i-- ) { int maxid = max( a, i + 1 ); int t = a[maxid]; a[maxid] = a[i]; a[i] = t; } for ( int i = 0; i < len; i++ ) { printf("%d ",a[i] ); } printf("\n"); int respond = 0; int k; printf("input you want to know element: \n"); respond = search(k, a, len ); printf("the way is: %d\n", respond ); return 0; }