算法程序与设计预习实验报告
一、二分搜索算法: 代码:
#include
int BinarySearch(int a[], int x, int n){ int left = 0; int right = x - 1; while(left<= right){
int middle = (left + right)/2; if(a[middle] left = middle + 1; else if(a[middle]>n) right = middle - 1; else return middle; } return -1; } main(){ int i, serch, fanhui; int a[10]={-24,-7,0,5,13,29,44,58,72,99}; for(i=0; i<10; i++) printf(\ printf(\请输入要找的数:\ scanf(\ fanhui = BinarySearch(a,10,serch); if(-1 == fanhui) printf(\查找失败 \\n\ else printf (\查找成功 \\n\} 运行结果: 二、合并排序: 代码: #include void Show(int c[], int n) { int i; for ( i=0; i } void Merge(int d[], int l, int m, int r) { int e[10]={0}; for (int i=l,int j=m+1,int k=0;k<=r-l;k++) { if (i==m+1) { e[k]=d[j++]; continue; } if (j==r+1) { e[k]=d[i++]; continue; } if (d[i] e[k]=d[i++]; } else { e[k]=d[j++]; } } for (i=l,j=0;i<=r;i++,j++) { d[i]=e[j]; } } void MergeSort(int b[], int left, int right) { if (left int i; i=(left+right)/2; MergeSort(b,left, i); MergeSort(b,i+1,right); Merge(b,left,i,right); } } int main() { int a[10] = { 58,0,-24,99,29,5,13,44,72,-7}; Show( a, 10); MergeSort( a, 0, 10-1 ); Show( a, 10); return 0; } 运行结果: 三、快速排序: 代码: #include int Partition(int b[], int p, int r){ int key; key=b[p]; while(p while(p b[p++]=b[r]; while(p b[r--]=b[p]; } b[p]=key; return p; } void QuickSort(int a[], int p, int r){ if (p int q= Partition(a,p,r); QuickSort(a,p,q-1); QuickSort(a,q+1,r); } return; } main(){ int i; int a[10]={58,0,-24,99,29,5,13,44,72,-7}; printf(\快排前 \\n\ for(i=0;i<10;i++) printf(\ QuickSort(a,0,9); printf(\快排后 \\n\ for(i=0; i<10; i++) printf(\ printf (\} 运行结果: