题目链接:6-11 求自定类型元素序列的中位数
一. 题目
1. 题目
2. 裁判程序样例
3. 输入输出样例
4. 限制
二、冒泡排序(超时)
1. 代码实现
void BubbleSort(ElementType *array, int len) {
ElementType tempNum;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (array[j] < array[j + 1]) {
tempNum = array[j];
array[j] = array[j + 1];
array[j + 1] = tempNum;
}
}
}
}
ElementType Median(ElementType A[], int N) {
BubbleSort (A, N);
return A[(N - 1) / 2];
}
2. 提交结果
三、选择排序(超时)
1. 代码实现
void SelectionSort(ElementType *array, int len) {
ElementType tempNum;
int max_index;
for (int i = 0; i < len; i++) {
max_index = i; // 初始最大值的下标
for (int j = i + 1; j < len; j++) {
if (array[max_index] < array[j]) { // 非最大
max_index = j; // 更新下标
}
}
if (max_index != i) { // array[i]非最大,交换
tempNum = array[i];
array[i] = array[max_index];
array[max_index] = tempNum;
}
}
}
ElementType Median(ElementType A[], int N) {
SelectionSort (A, N);
return A[(N - 1) / 2];
}
2. 提交结果
四、归并排序
1. 代码实现
#include <malloc.h>
#include <assert.h>
// 将两个降序序列进行合并
ElementType* Merge(ElementType *arrLeft, int lenLeft, ElementType *arrRight, int lenRight) {
int len = lenLeft + lenRight;
ElementType *new = malloc(len * sizeof(ElementType));
if (new == NULL) {
assert(0); // 防止内存分配失败
}
// 长度减一,便于赋值
lenLeft--;
lenRight--;
len--;
// 开始排序
while(lenLeft >= 0 && lenRight >= 0) {
// 最小的进行后置,=保证稳定性
if (arrRight[lenRight] <= arrLeft[lenLeft]) {
new[len--] = arrRight[lenRight--];
} else {
new[len--] = arrLeft[lenLeft--];
}
}
// 解决剩下的数
while (lenLeft >= 0) {
new[len--] = arrLeft[lenLeft--];
}
while (lenRight >= 0) {
new[len--] = arrRight[lenRight--];
}
return new;
}
ElementType* MergeSort(ElementType *arr, int len) {
if (len <= 1) { // 此时无需排序
return arr;
} else {
// 使用最小长度为1的两个短序列进行排序
int lenLeft = len / 2;
int lenRight = len - lenLeft;
return Merge(MergeSort(arr, lenLeft), lenLeft, MergeSort(arr + lenLeft, lenRight), lenRight);
}
}
ElementType Median(ElementType A[], int N) {
A = MergeSort(A,N);
return A[(N - 1) / 2];
}
2. 提交结果
五、总结
-
本题考察了排序算法,要求降序排列
-
测试点5说明要使用时间复杂度低的算法,相当于空间复杂度换时间复杂度
-
易错点:
(1)中位数:并非偶数长度时取中间两数求平均值
(2)第 [(N+1)/2] 大需要减去下标1,即为 [(N-1)/2] -
遗留问题:本题实现的归并排序没有对空间及时释放