#归并排序
归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。
思路:
1、先将数组一半一半分开,直到分成2个为一组时;
2、然后再对每2个数字组成的数组内部先进行排序
3、然后再对数组间进行合并;
4、如此递归下去,就形成了归并排序。
归并排序的时间复杂度为O(nlog2n),空间复杂度为O(n)
/*
实现:归并排序算法(递归版本)
*/
#include<iostream>
using namespace std;
void mergeArray(int a[], int start, int mid, int end){
int *temp = new int[end+1];
int i = start;
int j = mid + 1;
int index = start;
while (i <= mid&&j <= end){
if (a[i] < a[j]){
temp[index++] = a[i++];
}
else{
temp[index++] = a[j++];
}
}
while (i <= mid){
temp[index++] = a[i++];
}
while (j <= end){
temp[index++] = a[j++];
}
for (int k = start; k <= end; k++){
a[k] = temp[k];
}
}
void mergeSort(int a[], int start, int end){
if (start < end){
int mid = (start + end) / 2;
mergeSort(a, start, mid);
mergeSort(a, mid + 1, end);
//对两个数组进行合并,这2个数组是start ~ mid 以及 mid+1 ~ end
mergeArray(a, start, mid, end);
}
}
int main(){
int a[] = { 7, 5, 6, 4, 3, 2, 1, 3, 5, 7, 9 };
mergeSort(a,0,10);
for (int i = 0; i <= 10; i++){
cout << a[i] << " ";
}
system("pause");
return 0;
}
/*
实现:归并排序算法(非递归版本)
*/
#include<iostream>
#include<vector>
using namespace std;
void mergeArray(vector<int>& number, int start, int mid, int end) {
vector<int> tempNum(number.size(), 0);
int i = start;
int j = mid + 1;
int index = start;
while (i <= mid&&j <= end) {
if (number[i] < number[j]) {
tempNum[index++] = number[i++];
}
else {
tempNum[index++] = number[j++];
}
}
while (i <= mid) {
tempNum[index++] = number[i++];
}
while (j <= end) {
tempNum[index++] = number[j++];
}
for (int i = start; i <= end; i++) {
number[i] = tempNum[i];
}
}
void mergeSort(vector<int>& number) {
int step = 1;
int start, mid, end;
while (step <= number.size() - 1) {
start = 0;
while (start + step <= number.size() - 1) {
mid = start + step - 1;
end = start + step * 2 - 1;
if (end > number.size() - 1){
end = number.size() - 1;
}
mergeArray(number, start, mid, end);
start = end + 1;
}
step = step * 2;
}
}
int main() {
vector<int> number;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int temp;
cin >> temp;
number.push_back(temp);
}
mergeSort(number);
for (int i = 0; i < n; i++) {
cout << number[i] << " ";
}
system("pause");
return 0;
}