binarysearch.c
上传用户:bjtelijie
上传日期:2010-01-01
资源大小:87k
文件大小:2k
源码类别:

数学计算

开发平台:

Visual C++

  1. #include <stdio.h>
  2. #include <stdlib.h> 
  3. #include <string.h>
  4. #define NUM 4
  5. struct Data
  6. {
  7. char name[20];
  8. char city[20];
  9. char sex[10];
  10. char age[10];
  11. char job[10];
  12. };
  13. struct Data SDatas[NUM]=
  14. {
  15. "Sun","Weifang","Male","24","student",
  16. "Tom","Beijing","Male","31","doctor",
  17. "Marry","Shanghai","Female","19","techer",
  18. "Willing","Tianjing","Female","21","worker"
  19. };
  20. void qs_struct(items,left,right);
  21. void quick_struct(items,count);
  22. int BinarySeach(items,name,n);
  23. void print_data(point);
  24. int main(void)
  25. {
  26. char name[30];
  27. int i; 
  28. printf("将原始数据排序n");
  29. quick_struct(SDatas,NUM);
  30. printf("请输入要查找人的名字:n");
  31. scanf("%s",name);
  32. i = BinarySeach(SDatas,name,NUM);
  33. if(i == -1)
  34. {
  35. printf("没有查找到该人信息n");
  36. return 0;
  37. }
  38. printf("查找结果:n");
  39. print_data(&SDatas[i]);
  40. return 1;
  41. }
  42. void quick_struct(items,count)
  43. struct Data items[];
  44. int count;
  45. {
  46. qs_struct(items,0,count-1);
  47. }
  48. void qs_struct(items,left,right)
  49. struct Data items[];
  50. int left;
  51. int right;
  52. {
  53. register int i,j;
  54. char *x;
  55. struct Data temp;
  56. i = left;
  57. j = right;
  58. x = items[(left+right/2)].name;
  59. do
  60. {
  61. while((strcmp(items[i].name,x)<0)&&(i<right))
  62. i++;
  63. while((strcmp(items[j].name,x)>0)&&(j>left))
  64. j--;
  65. if(i<=j)
  66. {
  67. temp = items[i];
  68. items[i] = items[j];
  69. items[j] = temp;
  70. i++;
  71. j--;
  72. }
  73. }while(i<=j);
  74. if(left<j)
  75. qs_struct(items,left,j);
  76. if(i<right)
  77. qs_struct(items,i,right);
  78. }
  79. int BinarySeach(items,name,n)
  80. struct Data items[];
  81. char name[];
  82. int n;
  83. {
  84. int low,high,mid;
  85. low = 0;
  86. high = n-1;
  87. while(low<=high)
  88. {
  89. mid = (low+high)/2;
  90. if((strcmp(items[mid].name,name)==0))
  91. return mid;
  92. else if((strcmp(items[mid].name,name)<0))
  93. low = mid+1;
  94. else high = mid-1;
  95. }
  96. return -1;
  97. }
  98. void print_data(point)
  99. struct Data *point;
  100. {
  101. if(point ==NULL)
  102. return;
  103. printf(" 姓名:%sn",point->name);
  104. printf(" 城市:%sn",point->city);
  105. printf(" 性别:%sn",point->sex);
  106. printf(" 年龄:%sn",point->age);
  107. printf(" 工作:%sn",point->job);
  108. }