当前位置:   article > 正文

利用快速排序和二分查找数字出现次数

快速排序第三趟排序结果计算二分查找的查询次数

 

 

  1. #include <windows.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <time.h>
  5. #include <ctime>
  6. #include <algorithm>
  7. #define ARRLEN 1000
  8. using namespace std;
  9. int arr[ARRLEN];
  10. int Patition(int arr3[], int low, int high)
  11. {
  12. int pivotkey=arr3[low];
  13. int temp = arr3[low];
  14. while(low<high)
  15. {
  16. while(low <high && arr3[high]>=pivotkey)
  17. {
  18. --high;;
  19. }
  20. arr3[low]=arr3[high];
  21. while(low<high && arr3[low]<=pivotkey)
  22. {
  23. ++low;;
  24. }
  25. arr3[high]=arr3[low];
  26. }
  27. arr3[low] = temp;
  28. return low;
  29. }
  30. void QuickSort(int arr3[], int low, int high)
  31. {
  32. if(low<high)
  33. {
  34. int pivotloc=Patition(arr3,low, high);
  35. QuickSort(arr3, low, pivotloc-1);
  36. QuickSort(arr3, pivotloc+1, high);
  37. }
  38. }
  39. int BinarySearch(int arr[],int start,int end,int key){
  40. if (arr[start]==key)
  41. return start;
  42. if (arr[end]==key)
  43. return end;
  44. while(start<end){
  45. int mid=(start+end)/2;
  46. if (arr[mid]==key){
  47. return mid;
  48. }
  49. if (arr[mid]>key)
  50. end=mid-1;
  51. else
  52. start=mid+1;
  53. }
  54. if(start>=end)
  55. return -1;
  56. }
  57. int SearchTheTimesOfK(int arr[],int start,int end,int key){
  58. int index=BinarySearch(arr,0,ARRLEN-1,key);
  59. if(index==-1)return index;
  60. int firstindex=index,lastindex=index;
  61. while (firstindex>=0&&arr[firstindex]==key)
  62. firstindex--;
  63. while(lastindex<ARRLEN&&arr[lastindex]==key)
  64. lastindex++;
  65. return lastindex-firstindex-1;
  66. }
  67. void InitArr(){
  68. for (int i=0,j;i<ARRLEN;i++)
  69. {
  70. j=rand()%1000;
  71. arr[i]=j;
  72. }
  73. }
  74. void Display(int arr[],int n){
  75. int i=0;
  76. while(n--){
  77. printf("%d ",arr[i]);
  78. i++;
  79. }
  80. }
  81. int main(void){
  82. InitArr();
  83. QuickSort(arr,0,ARRLEN-1);
  84. Display(arr,ARRLEN);
  85. printf("\n");
  86. int times=SearchTheTimesOfK(arr,0,ARRLEN-1,999);
  87. if (times!=-1)
  88. printf("%d",times);
  89. else
  90. printf("找不到!");
  91. getchar();
  92. return 0;
  93. }

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/624484
推荐阅读
相关标签
  

闽ICP备14008679号