算法复习系列之——排序(冒泡排序、选择排序、插入排序、归并排序&小和问题)

#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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值