奇数个数寻找中位数,有O(N)复杂度的算法,这里采用的方式是先排序,然后找出中间那一个,等写到快排时在写线性时间的算法吧。
以下采用的方式分别是冒泡排序和堆排序:


1
#include<stdio.h>
2
#include<stdlib.h>
3
#define LEN 10010
4
void swap(int *a, int *b)
5

{
6
int t = *a;
7
*a = *b;
8
*b = t;
9
}
10
void bsort(int *a, int n)
11

{
12
int i, j;
13
for(j = n; j > 1; j--)
14
for(i = 1; i < j; i++)
15
{
16
if(a[i] > a[i + 1])
17
swap(&a[i], &a[i + 1]);
18
}
19
}
20
int main()
21

{
22
int i, j;
23
int N;
24
int a[LEN];
25
scanf("%d", &N);
26
for(i = 1; i <= N; i++)
27
scanf("%d", &a[i]);
28
bsort(a, N);
29
printf("%d\n", a[i / 2]);
30
31


1
#include<stdio.h>
2
#include<stdlib.h>
3
#define LEN 10010
4
void swap(int *a, int *b)
5

{
6
int t = *a;
7
*a = *b;
8
*b = t;
9
}
10
void f(int *a, int top, int r)
11

{
12
int j;
13
int t = a[top];
14
int top1 = top;
15
for(j = 2 * top; j <= r; j *= 2)
16
{
17
if(j < r && a[j] < a[j + 1])
18
j++;
19
if(a[j] < a[j / 2])
20
break;
21
int t = a[j];
22
a[j] = a[j / 2];
23
a[j / 2] = t;
24
}
25
}
26
void heapsort(int *a, int N)
27

{
28
int i, j;
29
for(i = N / 2; i >= 1; i--)
30
f(a, i, N);
31
for(i = N; i > 1; i--)
32
{
33
swap(&a[1], &a[i]);
34
f(a, 1, i - 1);
35
}
36
}
37
int main()
38

{
39
int i, j;
40
int N;
41
int a[LEN];
42
scanf("%d", &N);
43
for(i = 1; i <= N; i++)
44
scanf("%d", &a[i]);
45
heapsort(a, N);
46
printf("%d\n", a[i


#include<stdio.h>
#include<stdlib.h>
#define LEN 10010
void swap(int *a, int *b)


{
int t = *a;
*a = *b;
*b = t;
}
int Partition(int *a, int f, int r)


{
int i = f;
int j = r + 1;
int t = a[f];
while(1)

{
while(a[++i] < t && i < r);
while(a[--j] > t);
if(i >= j)
break;
swap(&a[i], &a[j]);
}
a[f] = a[j];
a[j] = t;
return j;
}
int Select(int *a, int f, int r, int k)


{
int j = Partition(a, f, r);
if(j == k + f - 1)
return a[j];
else if(j > k + f - 1)
return Select(a, f, j - 1, k);
else
return Select(a, j + 1, r, k + f - j - 1);
}
int main()


{
int i, j;
int N;
int a[LEN];
scanf("%d", &N);
for(i = 1; i <= N; i++)
scanf("%d", &a[i]);
int t = Select(a, 1, N, i / 2);
printf("%d\n", t);
//
//system("pause");
}

/ 2]);
47
48
//system("pause");
49
}
50
}
32
--------------------------------------
现在补上线性时间选择的方法:
posted on 2012-07-16 15:52
小鼠标 阅读(561)
评论(0) 编辑 收藏 引用 所属分类:
排序