#include<iostream>
#include<string>
using namespace std;
//三种排序算法
//1. 冒泡排序
void BubbleUp(string &str) {
int length = str.length();
for (int i = 0; i < length-1; i++)
{
for (int j = length - 1; j > i; j--) {
if (str[j] < str[j - 1]) {
int temp = str[j];
str[j] = str[j - 1];
str[j - 1] = temp;
}
}
}
}
//效果和up是一样的
void BubbleDown(string& str) {
int length = str.length();
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length-i-1; j++) {
if (str[j] < str[j + 1]) {
int temp = str[j];
str[j] = str[j + 1];
str[j + 1] = temp;
}
}
}
}
//2. 选择排序
void selection(string& str) {
int length = str.length();
for (int i = 0; i < length - 1; i++)
{
int lowest = i;
for (int j = length - 1; j > i; j--) {
if (str[j] < str[lowest]) {
lowest = j;
}
}
if (lowest != i) {
int temp = str[i];
str[i] = str[lowest];
str[lowest] = temp;
}
}
}
//3. 插入排序
void insertion(string & str) {
int length = str.length();
for (int i = 1; i < length; i++)
{
for (int j = i; (j > 0) && (str[j]<str[j-1]); j--) {
int temp = str[j];
str[j] = str[j -1];
str[j - 1] = temp;
}
}
}
int main() {
string s = "ahcuwskxo";
string s1 = s;
string s2 = s;
string s3 = s;
BubbleUp(s);
cout << s << endl;
BubbleDown(s1);
cout << s1 << endl;
selection(s2);
cout << s2 << endl;
insertion(s3);
cout << s3 << endl;
}
C++经典排序方法-冒泡排序-选择排序-插入排序
最新推荐文章于 2022-04-24 15:37:01 发布