码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序及折半查找

时间:2015-05-22 00:08:23      阅读:565      评论:0      收藏:0      [点我收藏+]

标签:

数据结构与算法---快速排序及折半查找:

1)编程实现数据序列的输入
2)实现快速排序算法,并对输入的序列排序后输出;

3)实现折半查找算法,并在步骤(2)排序后的序列上,进行任意地查找,并输出查询结果。(查找成功/不成功;等于关键值的元素个数=1或>1)

技术分享
  1 #include <stdio.h>
  2 #define N 100
  3 
  4 //快速排序算法并输出 
  5 void Quick_Partition(double *r, int i, int j)
  6 {
  7     double x = r[i];
  8     int low = i;
  9     int high = j;
 10     if (low < high)
 11     {
 12     while (i < j)
 13     {
 14         while(i < j && r[j] >= x)
 15         j--;
 16         if (i < j)
 17         {
 18             r[i] = r[j];
 19             i++;
 20         }
 21         while(i < j && r[i] <= x)
 22         i++;
 23         if (i < j)
 24         {
 25             r[j] = r[i];
 26             j--;
 27         }
 28     }
 29     r[i] = x;
 30     Quick_Partition(r, low, i - 1);
 31     Quick_Partition(r, i + 1, high);
 32     }
 33     else
 34     return;
 35 };
 36 
 37 //折半查找算法
 38 int BinarySearch(double *r, double key, int m, int n)
 39 {
 40     int low = m;
 41     int high = n;
 42     int mid;
 43     int x = 0, i = 0;
 44     while (low <= high)
 45     {
 46         mid = (low + high) / 2;
 47         if (r[mid] == key)
 48         {
 49             x++;
 50             for (i = mid + 1; i <= n && r[i] == key; i++)
 51                 x++;
 52             for (i = mid - 1; i >= m && r[i] == key; i--)
 53                 x++;
 54             return x;
 55         }
 56         else if (key > r[mid])
 57         low = mid + 1;
 58         else high = mid - 1;
 59     }
 60     
 61     return x;
 62 };
 63 
 64 
 65 int main(void)
 66 {
 67     FILE *fp;
 68     int i = 0, y, u;
 69     double n;
 70     double m[N] = {0};
 71     double x;
 72     
 73     fp = fopen("test.txt", "r");
 74     if(fp)
 75     while (fscanf(fp, "%lf", &n) != EOF)
 76     {
 77         m[i++] = n;
 78         if (i > 99)
 79         printf("输入数据数量超出!\n");
 80     }
 81     fclose(fp);
 82     
 83     y = i - 1;
 84     Quick_Partition(m, 0, y);
 85     
 86     printf("快速排序后输出:\n");
 87     for (i = 0; i <= y; i++)
 88     {
 89         printf("%.1lf\t", m[i]);
 90     }
 91     
 92     printf("\n请输入您想要查找的数:");
 93     scanf("%lf", &x);
 94 
 95     u = BinarySearch(m, x, 0, y);
 96 
 97     if (u == 0)
 98     printf("查找失败!\n");
 99     else
100     printf("查找成功,有%d个%.1lf\n", u, x);
101     
102     return 0;
103 }
快速排序及折半查找

在根目录下放置test.txt文件

技术分享
9.3 5.2 8 4.6 2 1.5 5 3 7.6 6.5 4 8 5 9 6 2.2 1 5
test.txt

 

快速排序及折半查找

标签:

原文地址:http://www.cnblogs.com/jywt/p/4520911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!