1.问题
分治算法求数组第k小元素
2.解析
将输入的数组分成n/5组元素,剩余的元素舍弃,取出每组的中项(即第三个)放在M[]中,取出M的中项mid(排序后取出中项),将原数组中所有数与mid比较,根据比较结果将原数组分成三组,再根据k值与三个数组大小的比较去相应的数组找要求的元素。
3.设计
void sort// 排序小规模的数组范围
void Select( input, size , k) //主函数
if size过小//直接sort ,return input[k];
q = size/5
for (i from 0 to size)
int M[i] = sort(from input[5i] to input[5i+5]) -> 3;
mid = Select(M,q,M/2);
for(i from 0 to size)
A1(count1++) = (input[i]<mid)
A2(count2++) = (input[i]=mid)
A3(count3++) = (input[i]>mid)
if (k<count1) return Select(A1,count1,k);
if(k< count1+count2) return mid;
else return Select(A3,count3,k-coun1-count2);
4.分析
算法复杂度:O(n)
5.源码
#include<stdio.h>
#include<stdlib.h>
void swap(int *x, int *y) {
int tmp = *x;
*x = *y;
*y = tmp;
}
void sort(int *input, int low, int high) {
for (int i = low; i <= high; i++) {
for (int j = low; j <= high - low - 1; j++) {
if (input[j] > input[j + 1])