C++容器排序算法的简单应用

/*
功能实现
1.去掉所有重复的单词
2.按照单词的长度进行排序
3.统计长度等于或者超过6个字符的单词个数
4.按照单词的长度顺序进行输出
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

bool isShorter(const string &s1 , const string &s2)
{
	return s1.size() < s2.size();
}

bool GT6(const string &s)
{
	return s.size() >= 6;
}
string make_plural(vector<string>::size_type cnt , string s1 , string s2)
{
	return (cnt == 1) ? s1 : s1+s2;  
}
int main()
{
	typedef vector<string>::iterator iter;
	typedef vector<string>::size_type sz_type;
	vector<string> words;
	string next_word;
	//输入单词
	while(cin >> next_word && next_word != "0")
	{//当输入0时结束
		words.push_back(next_word);
	}
	//对单词进行排序,按照字典序进行排列
	sort(words.begin() , words.end());
	//去掉重复的单词
	iter end_unique = unique(words.begin() , words.end());
	words.erase(end_unique , words.end());
	//对剩下没有重复的单词进行长度排序,长度相等的进行字典序排列
	stable_sort(words.begin() , words.end() , isShorter);
	//按长度输出剩下的单词
	for(iter it = words.begin() ; it != words.end() ; ++it)
	{
		cout << *it  << "  ";
	}
	cout << endl;
	//找到单词长度大于等于6个字符的个数
	sz_type wc = count_if(words.begin() , words.end() , GT6);
	cout << wc << make_plural(wc , "time" , "s") << endl;
	return 0;
}

C++中的快速排序是一种常用的高效排序算法,它的基本思想是通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,然后分别对这两部分继续进行排序,直到整个序列有序。快速排序通常使用递归的方式来实现。 在C++中,可以使用`std::vector`等内置的动态数组容器来存储待排序的数据。首先选择一个元素作为基准(pivot),一般是第一个或最后一个元素。然后,从左到右遍历数组,如果当前元素小于基准,就将其交换到基准的左边;反之,如果大于或等于基准,则留在右边。这个过程被称为分区操作。接着,递归地对基准左侧和右侧的子数组进行同样的排序。 以下是一个简单的快速排序C++示例,使用`std::vector`: ```cpp #include <vector> #include <algorithm> void quickSort(std::vector<int>& arr, int low, int high) { if (low < high) { // Partition operation int pivot = arr[high]; // Choose last element as pivot int i = low - 1; for (int j = low; j < high; ++j) { if (arr[j] <= pivot) { i++; std::swap(arr[i], arr[j]); } } std::swap(arr[i + 1], arr[high]); // Move pivot to its correct position int pi = i + 1; // Recursively sort two subarrays quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } // Usage example int main() { std::vector<int> numbers = {9, 7, 5, 11, 12, 2, 14, 3, 10}; quickSort(numbers, 0, numbers.size() - 1); for (const auto& num : numbers) { std::cout << num << " "; } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值