快速排序&&归并排序



#include <iostream>
#include <stdio.h>
using namespace std;
#define LEN 8
class SortAlgo
{
public:
	int *arr;
	int size;
	SortAlgo(int a[], int len)
	{
		this->arr = new int[len];
		this->size = 0;
		for (int i = 0; i < len; ++i)
		{
			arr[i] = a[i];
			++size;
		}
	}
	~SortAlgo() { delete arr; }
	void QuickSort(int *arr, int i, int j);
	void mergeSort(int *arr, int low, int high);
	void merge(int *arr, int begin, int middle, int end);
	int getSize();
	void show();
	void swap(int i, int j);
};
int SortAlgo::getSize()
{
	return this->size;
}
void SortAlgo::show()
{
	for (int i = 0; i < getSize(); ++i)
	{
		cout << arr[i] << " ";
	}
}
void SortAlgo::swap(int i, int j)
{
	arr[i] = arr[i] xor arr[j];
	arr[j] = arr[i] xor arr[j];
	arr[i] = arr[i] xor arr[j];
}
void SortAlgo::QuickSort(int *arr, int i, int j)
{
	if (i >= j)
		return;
	//基准数
	int base = arr[i];
	int end = j;
	while (i < j)
	{
		//scan from right to left
		while (arr[j] > base && j < i)
			--j;
		if (j > i)
			swap(i, j);
		//scan from left to right
		while (arr[i] < base && i < j)
			++i;
		if (j > i)
			swap(i, j);
		--j;
	}
	QuickSort(arr, 0, i);
	QuickSort(arr, i + 1, end);
}
void SortAlgo::mergeSort(int *arr, int low, int high)
{
	if (low < high)
	{
		int mid = (low + high) >> 1;
		mergeSort(arr, low, mid);
		mergeSort(arr, mid + 1, high);
		merge(arr, low, mid, high);
	}
}
void SortAlgo::merge(int *arr, int low, int mid, int high)
{
	// cout << low << " " << mid << " " << high << endl;
	//归病排序
	int temp[high - low + 1] = {0};
	//arr1 from low to mid
	//arr2 from mid+1 to high
	int index = 0;
	int i = low;
	int j = mid + 1;
	while (i <= mid || j <= high)
	{
		if (i > mid)
		{
			temp[index++] = arr[j++];
		}
		if (j > high)
		{
			temp[index++] = arr[i++];
		}
		while (i <= mid && arr[i] <= arr[j])
		{
			temp[index++] = arr[i++];
		}
		while (j <= high && arr[j] <= arr[i])
		{
			temp[index++] = arr[j++];
		}
	}
	index = 0;
	for (int i = low; i <= high; ++i, index++)
	{
		arr[i] = temp[index];
	}
}
int main()
{
	register int a[LEN] = {20, 15, 14, 0, 5, 4, 15, 16};
	SortAlgo Qs(a, LEN);
	Qs.show();
	cout << "sorting......" << endl;
	//Qs.QuickSort(Qs.arr,0,LEN-1);
	//Qs.show();
	Qs.mergeSort(a, 0, LEN - 1);
	Qs.show();
	return 0;
}

全部评论

相关推荐

一个菜鸡罢了:哥们,感觉你的简历还是有点问题的,我提几点建议,看看能不能提供一点帮助 1. ”新余学院“别加粗,课程不清楚是否有必要写,感觉版面不如拿来写一下做过的事情,教育经历是你的弱势就尽量少写 2. “干部及社团经历”和“自我评价”删掉 3. 论文后面的“录用”和“小修”啥的都删掉,默认全录用,问了再说,反正小修毕业前肯定能发出来 4. 工作经验和研究成果没有体现你的个人贡献,着重包装一下个人贡献
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务