// mySort.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//选择排序
void SelectionSort(int *a, int len) {//传入数组,以及遍历的len
int i, h, j, k, temp;
for (i = 0; i < len - 1; i++) {
k = i;
for (j = i + 1; j < len; j++) {
if (a[j] < a[k]) {
k = j;
}
}
if (k != i) {
temp = a[i];
a[i] = a[k];
a[k] = temp;
}
//输出每步排序的结果
cout << "第" << i << "步排序结果:\t";
for (h = 0; h < len; h++) {
cout << a[h] << "\t";
}
cout << endl << endl;
}
}
//冒泡排序算法
void BubblueSort(int *a, int len) {
int i, j, k, temp;
for (i = 0; i < len - 1; i++) {
for (j = len - 1; j > i; j--) {
if (a[j - 1] > a[j]) {//判断大小并交换
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
cout << "第" << i << "步排序结果:\t";
for (k = 0; k < len; k++) {
cout << a[k] << "\t";
}
cout << endl << endl;
}
}
//插入排序
void InsertionSort(int *a, int len) {
int i, j, t, h;
for (i = 1; i < len; i++) {
t = a[i];
j = i - 1;
while (j >= 0 && t < a[j]) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = t;
//输出每步排序的结果
cout << "第" << i << "步排序结果:\t";
for (h = 0; h < len; h++) {
cout << a[h] << "\t";
}
cout << endl << endl;
}
}
//希尔排序
void ShellSort(int *a, int len) {
int i, j, h;
int r, temp;
int x = 0;
for (r = len / 2; r >= 1; r /= 2) {
for (i = r; i < len; i++) {
temp = a[i];
j = i - r;
while (j >= 0 && temp < a[j]) {
a[j + r] = a[j];
j -= r;
}
a[j + r] = temp;
}
x++;
//输出每步排序的结果
cout << "第" << x << "步排序结果:\t";
for (h = 0; h < len; h++) {
cout << a[h] << "\t";
}
cout << endl << endl;
}
}
//快速排序
void QuickSort(int *a, int left,int right) {
int f, t;
int rtemp, ltemp;
ltemp = left;
rtemp = right;
f = a[(left + right) / 2];
while (ltemp < rtemp) {
while (a[ltemp] < f) {
++ltemp;
}while (a[rtemp] > f) {
--rtemp;
}
if (ltemp <= rtemp) {
t = a[ltemp];
a[ltemp] = a[rtemp];
a[rtemp] = t;
--rtemp;
++ltemp;
}
}
if (left == rtemp)
ltemp++;
if (ltemp < rtemp)
QuickSort(a, left, ltemp-1);
if (ltemp < right)
QuickSort(a, rtemp+1, right);
}
int main()
{
const int size = 5;
int shuzu[size];
int i;
//产生随机数
srand(time(nullptr));
for (i = 0; i < size; i++) {
shuzu[i] = rand() / 1000 + 10;
}
cout << "排序前数组为:\t";
for (i = 0; i < size; i++) {
cout << shuzu[i] << "\t";
}
cout << endl << endl;
//开始进行排序
cout << "请选择你要的排序算法:" << endl;
cout << "1.选择排序:" << endl;
cout << "2.冒泡排序:" << endl;
cout << "3.插入排序:" << endl;
cout << "4.希尔排序:" << endl;
cout << "5.快速排序:" << endl;
int num = 0;
cin >> num;
switch (num)
{
case 1:
cout << "选择排序:" << endl;
SelectionSort(shuzu, size);
break;
case 2:
cout << "冒泡排序:" << endl;
BubblueSort(shuzu, size);
break;
case 3:
cout << "插入排序:" << endl;
InsertionSort(shuzu, size);
break;
case 4:
cout << "希尔排序:" << endl;
ShellSort(shuzu, size);
break;
case 5:
cout << "快速排序:" << endl;
QuickSort(shuzu, 0, size - 1);
break;
default:
break;
}
cout << endl;
cout << "排序后数组为:\t";
for (i = 0; i < size; i++) {
cout << shuzu[i] << "\t";
}
cout << endl << endl;
system("pause");
return 0;
}
数据结构之排序算法
最新推荐文章于 2024-07-24 21:14:44 发布