Quicksort

21 篇文章 0 订阅
9 篇文章 0 订阅
#include <iostream>
#include <fstream>
#include <math.h>

using namespace std;

void PivotRules(int *arr, int n, int method)
{
	switch (method)
	{
	case 1:
		{
			// ----- select the first element ------
			break;
		}
	case 2:
		{
			// ------ select the last element -----
			int temp;
			temp = arr[n-1];
			arr[n-1]=arr[0];
			arr[0] = temp;
			break;
		}
	case 3:
		{
			// ----- select the median element -----
			int temp;
			int mid = (n-1)/2;
			int med = 0;

			if ((arr[0] <= arr[mid] & arr[mid] <= arr[n-1]) || (arr[0] >= arr[mid] & arr[mid] >= arr[n-1]))
				med = mid;
			else if ((arr[mid] <= arr[0] & arr[0] <= arr[n-1]) || (arr[mid] >= arr[0] & arr[0] >= arr[n-1]))
				med = 0;
			else
				med = n-1;

			if (med != 0)
			{
				temp = arr[0];
				arr[0] = arr[med];
				arr[med] = temp;
			}

			break;
		}
	default:
		{
			std::cout << "error";
		}
	}

}

int quicksort(int *arr, int n, int ncp, int method)
{
	if (n < 2)
		return ncp;
	ncp += n-1;

	PivotRules(arr, n, method);

	int temp;
	int ll = 1;
	int rr = 1;
	while (rr <n)
	{
		if (arr[rr] < arr[0])
		{
			temp = arr[ll];
			arr[ll] = arr[rr];
			arr[rr] = temp;
			ll++;
		}
		rr++;
	}

	// -------  exchange ------
	temp = arr[ll-1];
	arr[ll-1] = arr[0];
	arr[0] = temp;

	// -------  split -----------
	ncp = quicksort(arr, ll-1, ncp, method);
	ncp = quicksort(arr+ll, n-ll, ncp, method);
	return ncp;
}


int main()
{

	/*int arr[6] = {4,2, 5, 6, 1, 3};
	int n = 6;*/
	ifstream infile;
	infile.open("QuickSort.txt");


	int arr[100020];
	int temp[100020];
	int* ptr = &arr[0];
	int n=0;
	while(!infile.eof())
	{
		infile>>*ptr;
		ptr++;
		n++;
	}

	int ncp = 0;
	ncp = quicksort(arr, n-1, ncp, 3);
	cout << ncp << endl;


	infile.close();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值