求一个无序数组的中位数
中位数是将数组排序之后,数组个数为奇数时,取中间的即为中位数;数组个数为偶数时,取中间两个的平均值即为中位数。
思路一:
要取得中位数,即给数组排序,使用任意排序算法均可,然后按数组下标取其中位数。
PS:该方法很直观,此处不实现
思路二:
1.设数组元素为n个,且为奇数个时,取数组前(n+1)/2个元素建一个小堆
2.遍历数组剩余元素,如果比堆顶元素大即入堆,如果比堆顶元素小或等于堆顶元素,即舍弃,不入堆
3.遍历完数组元素时,堆顶即为中位数
PS:此处要使用STL中的优先级队列,博主需要见缝插针的介绍一下优先级队列
优先级队列:
优先队列不遵循队列先进先出的规则,而是根据队列中元素的优先权,优先权最大的先被取出。
优先级队列使用方法:
头文件: #include
声明方式:
1.普通声明:
priority_queue tty;
这个是使用STL里默认的排列顺序,即从大到小排列,建大堆
2.自定义优先级:
struct compare
{
bool operator()(int x, int y)
{
return x > y; //x,小的优先级高
}
};
代码实现:
#include
#include
#include
#include
#include
using namespace std;
struct compare
{
bool operator()(int x, int y)
{
return x > y; //x,小的优先级高
}
};
void HeapSort(int* arr, int len)
{
assert(arr);
int newlen = (len + 1) / 2; //用数组的一半多1长度建堆
priority_queue, compare> tty; //建小堆
for (int i = 0; i < newlen;i++)
{
tty.push(arr[i]);
}
//此时数组中一半+1的元素已经建成小堆,需要比较数组后面元素
for (int j = newlen; j < len; ++j)
{
//拿数组后半部分依次和堆顶比较,大于堆顶时入堆
if (arr[j]>tty.top())
{
tty.pop(); //要保持堆内元素个数不变
tty.push(arr[j]);
}
}
if (!tty.empty())
{
cout <
}
cout << endl;
}
void TestHeapSort()
{
int arr[] = { 58, 99, 66, 34, 21, 2, 0, 8, 7, 6, 5, 222222, 111, 888, 3 };
int len = sizeof(arr) / sizeof(arr[0]);
HeapSort(arr, len);
}
int main()
{
TestHeapSort();
system("pause");
return 0;
}