码迷,mamicode.com
首页 > 其他好文 > 详细

顺序统计量

时间:2015-04-11 17:36:05      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

顺序统计量有关算法得与快速排序的分割联系起来

#include <iostream>
#include <algorithm>
using namespace std;


typedef int index;
index Rand_Partition(int *a, index p, index r);
index Partition(int *a, index p, index r);
int Weighted_Median(int *a, double *w, int p, int r);
pair<index, double> Rand_Partition_W(int *a, double *w, int p, int r);

int Rand_Select_93(int *a, int *b, int p, int r, int i);
index Rand_Partition_93(int *a, int *w, int p, int r);
int Ex_93(int *a, int* b, int p, int r, int k);
//随机算法选择第i个顺序统计量
int Rand_Select(int *a, int p, int r, int i){
    if (p == r)
        return a[p];
    int q = Rand_Partition(a, p, r);
    int k = q - p + 1;
    if (k == i)
        return a[q];
    else if (k < i)
        return Rand_Select(a, q + 1, r, i - k);
    else return Rand_Select(a, p, q - 1, i);
}



index Partition(int *a, index p, index r){
    int i = p - 1, j = p;
    for (; j < r; ++j){
        if (a[j] <= a[r]){
            ++i;
            std::swap(a[i], a[j]);
        }
    }
    std::swap(a[i + 1], a[r]);
    return i + 1;
}

index Rand_Partition(int *a, index p, index r){
    int rand_q = p + rand() % (r - p + 1);
    std::swap(a[rand_q], a[r]);
    return Partition(a, p, r);
}


//带权中位数

int Weighted_Median(int *a, double *w, int p, int r){
    if (p == r)
        return a[p];
    pair<index,double> q = Rand_Partition_W(a, w,p, r);
    double sum = q.second + w[q.first];
    if (q.first == p)
    {
        if (sum >= 0.5)
            return a[p]; 
        else return Weighted_Median(a, w, p + 1, r);
    }
    if (sum< 0.5)
        return Weighted_Median(a, w, q.first + 1, r);
    else {
        if (q.second < 0.5)
            return a[q.first];
        else return Weighted_Median(a, w, p, q.first - 1);
    }
}

pair<index,double> Rand_Partition_W(int *a,double *w, int p, int r){
    int pivot = p + rand() % (r - p + 1);
    swap(a[pivot], a[r]);
    swap(w[pivot], w[r]);
    int i = p - 1, j = p;
    double sum=0;
    for (; j < r; ++j){
        if (a[j] <= a[r]){
            ++i;
            sum += w[j];
            swap(a[i], a[j]);
            swap(w[i], w[j]);
        }
    }
    swap(a[i + 1], a[r]);
    swap(w[i + 1], w[r]);
    return{ i + 1, sum };
}

 

顺序统计量

标签:

原文地址:http://www.cnblogs.com/Nastukashii/p/4417905.html

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