快速排序,堆排序,归并排序的c++实现

1.快速排序

#include
#include
using namespace std;
class quicksort
{
public:
	quicksort(vector&num):nums(num){}
	void sort(int low,int high);
	void sort_();
	void print();
private:
	vectornums;
};
void quicksort::sort(int low,int high)
{
	if (low < high)
	{
		int tmp = nums[low];
		int i = low, j = high;
		while (i < j)
		{
			while (j>i&&nums[j] >= tmp)
				j--;
			nums[i] = nums[j];
			while (j>i&&nums[i] < tmp)
				i++;
			nums[j] = nums[i];
		}
		nums[i] = tmp;
		sort(low, i - 1);
		sort(i + 1, high);
	}
}
void quicksort::sort_()
{
	int len = nums.size();
	int low = 0, high = len - 1;
	sort(low, high);
}
void quicksort::print()
{
	for (auto i : nums)
		cout << i << ' ';
}

2.归并排序

#include
#include
using namespace std;
class mergesort
{
public:
	mergesort(vector&num):nums(num){}
	void merge(int low, int high);
	void sort(int low,int mid, int high);
	void merge_();
	void print();
private:
	vectornums;
	vectorhelp;
};
void mergesort::merge(int low, int high)
{
	if (low == high)
		return;
	int mid = (high-low)/2 + low;
	merge(low, mid);
	merge(mid + 1, high);
	sort(low, mid,high);
}
void mergesort::sort(int low,int mid,int high)
{
	int k = low;
	int i = low, j = mid + 1;
	while (i <= mid && j <= high)
	{
		if (nums[i] > nums[j])
			help[k++] = nums[j++];
		else
			help[k++] = nums[i++];
	}
	while (i <= mid)
		help[k++] = nums[i++];
	while (j <= high)
		help[k++] = nums[j++];
	for (int p = low; p <= high; p++)
		nums[p] = help[p];
}
void mergesort::merge_()
{
	int len = nums.size();
	help.resize(len);
	merge(0, len - 1);
	
}
void mergesort::print()
{
	for (auto i : nums)
		cout << i << ' ';
}

3.堆排序

#include
#include
#include
using namespace std;
class heapsort
{
public:
	heapsort(vector&num):nums(num){}
	void makeheap();
	void sort();
	void adjustheap(int i,int len);
	void printheap();
private:
	vectornums;
};
void heapsort::makeheap()
{
	int len = nums.size();
	for (int i = len / 2-1; i >= 0; i--)
	{
		adjustheap(i, len);
	}
}
void heapsort::adjustheap(int i, int len)
{
	int tmp = nums[i];
	int j = 2 * i + 1;
	while (j < len)
	{
		if (j + 1 < len&&nums[j] < nums[j + 1])
		{
			j++;
		}
		if (tmp > nums[j])
			break;
		nums[i] = nums[j];
		i = j;
		j = i * 2 + 1;
	}
	nums[i] = tmp;
}
void heapsort::sort()
{
	for (int i = nums.size() - 1; i >= 0; i--)
	{
		swap(nums[i], nums[0]);
		adjustheap(0, i);
	}
}
void heapsort::printheap()
{
	for (auto i:nums)
		cout << i << ' ';
}

三个排序方法都是直接相比较的,因为平均时间复杂度都为nlogn
     

你可能感兴趣的:(快速排序,堆排序,归并排序的c++实现)