用函数实现二分查找
#include <stdio.h> int binary_search(int arr[], int n, int k); #define SIZE 10 int main( ) { int d[SIZE] = {1, 3, 9, 12, 32, 41, 45, 62, 75, 77}; int low, high,mid,key,index=-1; printf("Input a key you want to search: "); scanf("%d" , &key); index = binary_search(d, SIZE, key); if(index >= 0) printf("The index of the key is %d .\n", index); else printf("Not found.\n"); return 0; } /* 功能:在长度为n的有序数组中查找k出现的位置 */ int binary_search(int arr[], int n, int k) { int i=-1; int low=0,high=n-1,mid; while(low<=high) { mid=(low+high)/2; if(arr[mid]==k) { i=mid; break; } else if(arr[mid]>k) high=mid-1; else low=mid+1; } return i; }
用函数实现选择法算法
#include <stdio.h> int main( ) { void select_sort(int array[],int n); //函数声明 int a[10]= {4,3,7,9,1,5,0,8,2,6},i; select_sort(a,10); //函数调用,数组名作实参 printf("the sorted array:\n"); for(i=0; i<10; i++) //输出10个已排好序的数 printf("%d ", a[i]); printf("\n"); return 0; } void select_sort(int array[],int n) //形参array是数组名 { int i,j,k,t; for(i=0; i<n-1; i++) { k=i; //先设第i个就为最小 for(j=i+1; j<n; j++) if(array[j]<array[k]) k=j; //通过循环,得到k为最小 t=array[k]; //交换a[i]和a[k] array[k]=array[i]; array[i]=t; } return; }
时间: 2024-12-02 14:42:47