#include<iostream>
using namespace std;
void Sort_Maopao(int *arr, int len);
void Sort_Select(int *arr, int len);
void Sort_Insert(int *arr, int len);
void Print_Array(int *arr, int len);
void Swap(int &a,int &b);
int Sort_Merge(int arr[], int len);
int SortProcess(int arr[], int Left, int Right);
int Merge(int arr[], int Left, int Middle, int Right);
int main()
{
//int arr[] = { 1,4,22,8,7,9 };
int arr[] = { 1,1,2 };
int len = sizeof(arr) / sizeof(*arr);
//冒泡排序
//Sort_Maopao(arr, len);
//Print_Array(arr, len);
//选择排序
//Sort_Select(arr, len);
//Print_Array(arr, len);
//插入排序
//Sort_Insert(arr, len);
//Print_Array(arr, len);
//归并排序
int res = Sort_Merge(arr, len);
cout << "***" << res << endl;;
Print_Array(arr,len);
system("pause");
return 0;
}
void Sort_Maopao(int *arr, int len) {
for (int i = 0; i < len; i++) {
for (int j = i; j < len - i; j++) {
if (arr[j] > arr[j + 1])
Swap(arr[j], arr[j + 1]);
}
}
}
//选择排序
void Sort_Select(int *arr, int len) {
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
if (arr[j] < arr[i])
Swap(arr[i],arr[j]);
}
}
}
//打印数组
void Print_Array(int *arr, int len) {
for (int i = 0; i < len; i++) {
cout << *arr++<<"\t";
}
cout << endl;
}
//交换
void Swap(int &a, int &b)
{
a = a + b;
b = a - b;
a = a - b;
}
//插入排序
void Sort_Insert(int *a, int len) {
for (int i = 1; i < len; i++) {
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
//归并排序&小和问题
int Sort_Merge(int arr[],int len) {
if (arr == nullptr || len < 2) {
return 0;
}
int res = SortProcess(arr,0,len - 1);
return res;
}
int SortProcess(int arr[], int Left, int Right) {
if (Left == Right) {
return 0;
}
//int Middle = Left + ((Right - Left) >> 1);
int Middle = (Left + Right)/2 ;
SortProcess(arr, Left, Middle);
SortProcess(arr,Middle + 1,Right);
int res = Merge(arr, Left, Middle, Right);
return res;
}
int Merge(int arr[], int Left, int Middle, int Right) {
int *Temp_Arr = new int[Right - Left + 1];
int L = Left;
int M = Middle + 1;
int i = 0;
int res = 0;
while (L <= Middle && M <= Right) {
res += arr[L] < arr[M] ? (Right - M + 1) * arr[L] : 0;
Temp_Arr[i++] = arr[L] < arr[M] ? arr[L++] : arr[M++];
}
while (L <= Middle) {
Temp_Arr[i++] = arr[L++];
}
while (M <= Right) {
Temp_Arr[i++] = arr[M++];
}
for (int j = 0; j < (Right - Left + 1); j++) {
arr[Left + j] = Temp_Arr[j];
}
return res;
}