首页 > 其他 > 详细

PTA——6-11 求自定类型元素序列的中位数 (25分)

时间:2020-01-26 10:04:49      阅读:172      评论:0      收藏:0      [点我收藏+]

采用希尔排序

 1 #include <stdio.h>
 2 
 3 #define MAXN 10
 4 typedef float ElementType;
 5 
 6 ElementType Median( ElementType A[], int N );
 7 
 8 int main ()
 9 {
10     ElementType A[MAXN];
11     int N, i;
12 
13     scanf("%d", &N);
14     for ( i=0; i<N; i++ )
15         scanf("%f", &A[i]);
16     printf("%.2f\n", Median(A, N));
17 
18     return 0;
19 }
20 
21 ElementType Median( ElementType A[], int N ){
22     int h = 1;
23     while( h < N/2 )
24         h = 2 * h + 1;
25     while( h >= 1 ){
26         for( int i = h ; i < N ; i ++ ){
27             ElementType e = A[i];
28             int j;
29             for( j = i ; j >= h && e < A[j-h] ; j -= h )
30                 A[j] = A[j-h];
31             A[j] = e;
32         }
33         h /= 2;
34     }
35     return A[N/2];
36 }
  • 希尔排序比常用的O(n^2)排序要快,采用其他排序算法会超时
  • 间隔可任意设置
  • 返回A[N/2]

PTA——6-11 求自定类型元素序列的中位数 (25分)

原文:https://www.cnblogs.com/cxc1357/p/12233767.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!