标签:sub 改进 namespace val 下意识 for fine 开始 之一
1 //插值查找 2 #include <iostream> 3 #include <stdlib.h> 4 #include <ctime> 5 6 using namespace std; 7 8 #define MAX 100 9 //数组输入 10 void input(int *arr) 11 { 12 srand((unsigned)time(NULL)); 13 for(int i = 0; i < MAX; i++) 14 { 15 arr[i] = rand()%100; 16 } 17 } 18 //数组输出 19 void output(int *arr) 20 { 21 for(int i = 0; i < MAX; i++) 22 { 23 cout << arr[i] << " "; 24 if(0 == i % 10) 25 cout << endl; 26 } 27 cout << endl; 28 } 29 //快速排序 30 void quickSort(int *arr, int l, int h) 31 { 32 if(l < h) 33 { 34 int low, high, tmp; 35 low = l; 36 high = h; 37 38 tmp = arr[l];//选择基准值 39 //将数组按照基准值分为两部分 40 while(low < high) 41 { 42 while(low < high && arr[high] > tmp) 43 high--; 44 if(low < high) 45 arr[low++] = arr[high]; 46 while(low < high && arr[low] < tmp) 47 low++; 48 if(low < high) 49 arr[high--] = arr[low]; 50 } 51 arr[low] = tmp; 52 //递归排序 53 quickSort(arr, l, low-1); 54 quickSort(arr, low+1, h); 55 } 56 } 57 //插值查找 58 int insertionSearch(int *arr, int value, int low, int high) 59 { 60 //相比 61 int mid = low + ((value - arr[low])/(arr[high] - arr[low]))*(high - low); 62 63 if(arr[mid] == value) 64 return mid; 65 if(arr[mid] > value) 66 return insertionSearch(arr, value, low, mid-1); 67 if(arr[mid] < value) 68 return insertionSearch(arr, value, mid+1, high); 69 } 70 71 int main() 72 { 73 int x, pos, num[MAX]; 74 input(num); 75 76 cout << "sort before:" << endl; 77 output(num); 78 quickSort(num, 0, MAX-1); 79 cout << "sort after:" << endl; 80 output(num); 81 82 cout << "Enter find num : "; 83 cin >> x; 84 85 pos = insertionSearch(num, x, 0, MAX-1); 86 87 if(pos) 88 cout << "OK!" << x << "is found in pos : " << pos << endl; 89 else 90 cout << "Sorry!" << x << "is not found in num" << endl; 91 92 return 0; 93 }
标签:sub 改进 namespace val 下意识 for fine 开始 之一
原文地址:https://www.cnblogs.com/Long-w/p/9798816.html