C语言描述:
#include <stdio.h> // 二分查找函数 int binarySearch(int arr[], int left, int right, int target) { while (left <= right) { int mid = left + (right - left) / 2; // 如果目标值等于中间值,则返回中间值的索引 if (arr[mid] == target) return mid; // 如果目标值小于中间值,则在左半部分继续查找 if (arr[mid] > target) right = mid - 1; // 如果目标值大于中间值,则在右半部分继续查找 else left = mid + 1; } // 如果未找到目标值,则返回-1 return -1; } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int n = sizeof(arr) / sizeof(arr[0]); int target; scanf("%d",&target); int result = binarySearch(arr, 0, n - 1, target); if (result != -1) printf("%d\n",result); else printf("未找到目标值"); return 0; }
汇编语言:
INCLUDE Irvine32.inc .data Numbers DWORD 1,3,7,9,12,13,34,35,88,999,1011,1013 LEN DWORD ($-Numbers)/4 input DWORD ? result DWORD ? prompt BYTE "Enter a number to search for: ", 0 .code main PROC mov EDX, OFFSET prompt call WriteString ; 读取用户输入的数 call ReadInt mov input, EAX ; 执行二分查找 mov EBX, OFFSET Numbers mov ECX, LEN mov EDX, input call BinarySearch ; 检查查找结果并输出 cmp result, -1 je not_found mov EAX, result call WriteDec jmp end_prog not_found: mov EDX, OFFSET prompt call WriteString mov EAX, input call WriteDec mov EDX, OFFSET not_found_msg call WriteString end_prog: call Crlf call WaitMsg exit main ENDP BinarySearch PROC push ECX push ESI push EDI ;check parameters CMP EBX,0 JZ FAIL CMP ECX,0 JZ FAIL mov ESI,0 mov EDI,ECX Dec EDI L1: mov ECX,ESI add ECX,EDI SAR ECX,1 mov EAX,[EBX+ECX*4] CMP EAX,EDX JZ SUCCESS CMP ESI,EDI JZ FAIL CMP EAX,EDX JG GREATER ;if EAX<EDX Mov ESI,ECX Inc ESI jmp L1 ;if EAX>EDX GREATER: MOV EDI,ECX Dec EDI jmp L1 SUCCESS: Mov result, ECX jmp FINISH FAIL: Mov result,-1 jmp FINISH FINISH: pop EDI pop ESI pop ECX ret BinarySearch ENDP not_found_msg BYTE " not found in the array.", 0 END main
运行结果: