冒泡排序 选择排序 插入排序
#include <iostream>
#include <time.h>
using namespace std;
void GetStr(int str[], int len)
{
srand((unsigned)time(NULL));
for (int i = 0; i < len; i++) {
str[i] = 24 + rand() % 10;
}
cout << "Before sort str is: " << endl;
}
void PrintStr(int str[], int len)
{
for (int i = 0; i < len; i++) {
cout << str[i] << " ";
}
cout << endl;
}
void Swap(int str[], int i, int j)
{
int tmp = 0;
tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
void BubbleSort(int str[], int len)
{
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (str[j] < str[j + 1]) {
Swap(str, j, j + 1);
}
}
}
cout << "After bubble sort str is : " << endl;
}
void SelectSort(int str[], int len)
{
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (str[i] < str[j]) {
Swap(str, i, j);
}
}
}
cout << "After select sort str is : " << endl;
}
void InsertSort(int str[], int len)
{
for (int i = 1; i < len; i++) {
for (int j = i; j > 0; j--) {
if (str[j] < str[j - 1]) {
Swap(str, j, j - 1);
}
}
}
cout << "After insert sort str is : " << endl;
}
int main(int argc, char* argv[])
{
int str[10] = {0};
int len = sizeof(str) / sizeof(str[0]);
GetStr(str, len);
PrintStr(str, len);
InsertSort(str, len);
PrintStr(str, len);
return 0;
}