#include<stdio.h> #include<math.h> #include<malloc.h> #include<string.h> #include<stdlib.h> #include <time.h> /* 冒泡排序 */ void rankNum(int num[],int n){ int i,j,t; for(i=0;i<n;i++){ for(j=0;j<n-i-1;j++){ if(num[j]>num[j+1]){ t=num[j]; num[j]=num[j+1]; num[j+1]=t; } } } } /* 选择排序 */ void rankNum02(int num[],int n){ int i,j,t,k; for(i=0;i<n;i++){ k=i; for(j=i+1;j<n;j++){ if(num[j]<num[k]){ k=j; } } if(k!=i){ t=num[i]; num[i]=num[k]; num[k]=t; } } } /* 插入排序 */ void rankNum03(int num[],int n){ int i,j,k; for(i=1;i<n;i++){ k=num[i]; j=i-1; while(j>=0&&num[j]>k){ num[j+1]=num[j]; j--; } num[j+1]=k; } } /* 二分插入法: */ void rankNum04(int num[],int n){ int i,j,k,low,high,mid; for(i=1;i<n;i++){ k=num[i]; low=0; high=i-1; while(low<=high){ mid=(high+low)/2; if(num[mid]>k){ high=mid-1; }else{ low=mid+1; } } for(j=i-1;j>=high+1;j--){ num[j+1]=num[j]; } num[high+1]=k; } } /* 希尔排序 */ void rankNum05(int num[],int n){ int i,j,k,gap=n/2; while(gap>0){ for(i=gap;i<n;i++){ j=i-gap; k=num[i]; while(j>=0&&num[j]>k){ num[j+gap]=num[j]; j=j-gap; } num[j+gap]=k; } gap=gap/2; } } /* 快排 */ void rankNum06(int num[],int low,int high){ if(low>=high) return; int i=low,j=high,k=num[low]; while(i<j){ while(i<j&&num[j]>=k){ j--; } num[i]=num[j]; while(i<j&&num[i]<=k){ i++; } num[j]=num[i]; } num[i]=k; rankNum06(num,low,i-1); rankNum06(num,i+1,high); } /* 二分查找 */ int binarySearch(int num[],int n,int target){ int low=0,high=n-1,mid,rs=0; while(low<=high){ mid=(low+high)/2; if(num[mid]>target){ high=mid-1; }else if(num[mid]<target){ low=mid+1; }else{ return mid+1; } } return rs; } /* 去掉重复值 */ int clearNum(int num[],int n){ int i,j,k; k=0; for(i=0;i<n;i++){ if(num[i]!=num[i+1]){ num[k]=num[i]; k++; } } n=k; return n; } /* 打印结果 */ void print(int num[],int n){ int i; for(i=0;i<n;i++){ printf("%d ",num[i]); } printf(" "); } main() { int n=10,num[n]={0,1,1,0,1,2,4,3,3,2}; //rankNum04(num,n); rankNum06(num,0,n); print(num,n); n=clearNum(num,n); print(num,n); printf("%d ",binarySearch(num,n,3)); }