关于使用c++完成快速排序算法

/*
输入一串字符,可以是多行,最后以'#'字符结尾
输出的结果是将单词按照ASCII升序输出的
*/
#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::endl;
using std::string;

void swap(string* pStr[], int first, int second);
void sort(string* pStr[], int start, int end);
int count_words(const string& text, const string& separators);
void extract_words(string* pStr[], const string& text, const string& separators);
void show_words(string* pStr[], int count);

int main()
{
	string text;
	const string separators = " ,.\n\"";	//定义分隔符

	cout << endl << "Enter a string terminated by #: " << endl;
	std::getline(cin, text, '#');

	int word_count = count_words(text, separators);
	if (word_count == 0)
	{
		cout << endl << "No words in text." << endl;
		return 0;
	}

	string** pWords = new string * [word_count];

	extract_words(pWords, text, separators);

	sort(pWords, 0, word_count - 1);

	show_words(pWords, word_count);
	return 0;
}

//计算输入的字符串中,一共包含多少个单词
int count_words(const string& text,  const string& separators)
{
	int count, start, end;
	count = 0; 
	start = text.find_first_not_of(separators);
	end = 0;
	while (start != string::npos)
	{
		end = text.find_first_of(separators, start + 1);
		if (end == string::npos)
			end = text.length();
		count++;
		start = text.find_first_not_of(separators, end + 1);
	}
	return count;
}

//将单词分割出来,放入string数组中
void extract_words(string* pStr[], const string& text, const string& separators)
{
	int count, start, end;
	count = 0; 
	start = text.find_first_not_of(separators);
	end = 0;
	while (start != string::npos)
	{
		end = text.find_first_of(separators, start + 1);
		if (end == string::npos)
			end = text.length();
		pStr[count++] = new string(text.substr(start, end - start));
		start = text.find_first_not_of(separators, end + 1);
	}
}

//快速排序算法
void sort(string* pStr[], int start, int end)
{
	if (start > end)
		return;

	swap(pStr, start, (start + end) / 2);

	int current = start;
	for(int i=start+1; i<=end; i++)
		if(*(pStr[i]) < *(pStr[start]))
			swap(pStr, ++current, i);

	swap(pStr, start, current);

	sort(pStr, start, current - 1);
	sort(pStr, current + 1, end);
}

//交换两个位置的数据
void swap(string* pStr[], int first, int second)
{
	string* temp = pStr[first];
	pStr[first] = pStr[second];
	pStr[second] = temp;
}

void show_words(string* pStr[], int count)
{	
	for (int i = 0; i < count; i++)
		cout << " " << *(pStr[i]);
}

** 其实,快速排序算法的核心,就是到分解为两两为一组的小事件,而这每两两一组之间又都满足升序或者降序规则,最后,将两两一组的小事件比较大小,就完成了排序**

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

able陈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值