二分排序算法
1. 问题
对n个不同的数构成的数组A[1..n]进行排序,其中n=2^k
2. 解析
归并排序是一种基于“归并”思想的排序方法,二分归并的原理是,将序列两两分组,将序列归并为n/2个组,组内单独排序,然后将这些组再两两归并,生成n/4个组,依次类推。实现排序
3. 设计
void merge(int a[], int l1, int r1, int l2, int r2) {
int i = l1, j = l2;
int temp[maxn], index = 0;
while (i <= r1 && j <=r2) {
if (a[i] <= a[j]) {
temp[index++] = a[i++];
}
else {
temp[index++] = a[j++];
}
}
while (i<=r1){
temp[index++] = a[i++];
}
while (j<=r2){
temp[index++] = a[j++];
}
for (i = 0; i < index; i++) {
a[l1 + i] = temp[i];
}
}
void mergeSort(int a[]) {
for (int step = 2; step / 2 <= n; step *= 2) {
for (int i = 1; i <= n; i += step) {
int mid = i + step / 2 - 1;
if (mid + 1 <= n){
merge(a, i, mid, mid + 1, min(i + step - 1, n));
}
}
}
}
4. 分析
时间复杂度是O(logn)
5. 源码
#pragma warning(disable:4996)
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
#define MAX_SIZE 100
#define ARR_SIZE 10
#define START 1
typedef struct {
int key;
}element;
void merge(element a[], int left, int middle, int right) {
element* map = (element*)malloc(sizeof(int) * MAX_SIZE);
int index = 0;
int i = left, j = middle + 1;
while (i <= middle && j <= right) {
if (a[i].key < a[j].key) {
map[index++].key = a[i++].key;
}
else {
map[index++].key = a[j++].key;
}
}
while (i <= middle) {
map[index++].key = a[i++].key;
}
while (j <= right) {
map[index++].key = a[j++].key;
}
for (int k = left; k <= right; k++) {
a[k].key = map[k - left].key;
}
}
void mergesort(element a[], int left, int right) {
if (left >= right) {
return;
}
int middle = (left + right) / 2;
mergesort(a, left, middle);
mergesort(a, middle + 1, right);
merge(a, left, middle, right);
}
int main() {
int i;
element arr[MAX_SIZE];
srand(time(NULL));
for (i = 1; i <= ARR_SIZE; i++) {
scanf("%d", &arr[i].key);
}
for (i = 1; i <= ARR_SIZE; ++i) {
printf("%d ", arr[i].key);
}
printf("\n");
mergesort(arr, START, ARR_SIZE);
for (i = 1; i <= ARR_SIZE; i++) {
printf("%d ", arr[i].key);
}
printf("\n");
return 0;
}