第二章
#include <stdio.h> #include <stdlib.h> #include <time.h> //插入排序 void InsertSort(int A[], int n) { int i, j, key; for(i=1; i<n; i++) { key = A[i]; j = i-1; while(A[j] > key && j>=0) { A[j+1] = A[j]; j--; } A[j+1] = key; } } //递归的插入排序 void InsertSortD(int A[],int n) { int i; int iTemp; if (n > 1) { InsertSort(A,n-1); iTemp = A[n-1]; for (i = n-2;i >= 0 && A[i] >iTemp;--i) A[i+1] = A[i]; A[i+1] = iTemp; } } //迭代的二分查找 int BinarySearch(int A[], int n, int x) { int low; int high; int mid; low = 0; high = n-1; while (low <= high) { mid = low + (high - low) / 2; if (x == A[mid]) return mid; else if (A[mid] > x) high = mid - 1; else low = mid + 1; } return -1; } //递归的二分查找的代码 int BinarySearch2(int A[],int low, int high, int x) { int mid; if (low > high) return -1; mid = low + (high-low)/2; if (A[mid] < x) return BinarySearch2(A,mid+1,high,x); else if (A[mid] > x) return BinarySearch2(A,low,mid-1,x); else return mid; } int main() { int i; int A[10]; srand(time(NULL)); for (i = 0; i < 10; ++i) { A[i] = rand() % 20; printf("%d ",A[i]); } printf("\n"); InsertSort(A,10); for (i = 0; i < 10; ++i) printf("%d ",A[i]); printf("\n"); printf("%d \n",BinarySearch2(A,0,9,6)); return 0; }
//二分插入排序 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> //迭代的二分查找查找第一个不小于x的数的位置 int BinarySearch(int A[], int n, int *i,int x) { int low; int high; int mid; low = 0; high = n-1; while (low <= high) { mid = low + (high - low) / 2; if (x == A[mid]) { *i = mid + 1; return 1; } else if (A[mid] > x) high = mid - 1; else low = mid + 1; } *i = low; return 0; } //二分插入排序 void BinaryInsertSort(int A[], int n) { int i; int iPos; int iTemp; for (i = 1; i <= n-1; ++i) { iTemp = A[i]; BinarySearch(A,i,&iPos,iTemp); memmove(A+iPos+1,A+iPos,(i-iPos)*sizeof(int)); A[iPos] = iTemp; } } int main() { int i; int A[10]; srand(time(NULL)); for (i = 0; i < 10; ++i) { A[i] = rand() % 20; printf("%d ",A[i]); } printf("\n"); BinaryInsertSort(A,10); for (i = 0; i < 10; ++i) printf("%d ",A[i]); printf("\n"); return 0; }