虽然写这个博客主要目的是为了给我自己做一个思路记忆录,但是如果你恰好点了进来,那么先对你说一声欢迎。我并不是什么大触,只是一个菜菜的学生,如果您发现了什么错误或者您对于某些地方有更好的意见,非常欢迎您的斧正!
选择排序:每次遍历没有排序的数组,从中选出最小的数,放到最前面。
这个排序一句话就可以概括了,反正我懂了,如果你不懂的话就推荐你去看这个网站:https://www.cnblogs.com/shen-hua/p/5424059.html
对排序有兴趣的朋友可以看一下这篇文章,我觉得写的非常好,主要是它有动图详解,非常适合想要了解这些排序的朋友!
https://www.cnblogs.com/onepixel/articles/7674659.html
下面是我的代码(建议复制到VS或其它编辑器进行理解):
选择排序.h
#pragma once
typedef int dataType;
/*打印数组*/
void PrintChooseArray(dataType arr[], int length);
/*数组初始化*/
void InitChooseArray(dataType arr[], int length);
/*交换数字*/
void Swap(dataType *a, dataType *b);
/*选择排序*/
void ChooseSort(dataType arr[], int length);
/*测试选择排序*/
void TestChooseSort();
选择排序.cpp
#include "选择排序.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
/*打印数组*/
void PrintChooseArray(dataType arr[], int length)
{
for (int i = 0; i < length; i++)
{
cout << arr[i] << " ";
if ((i + 1) % 10 == 0)/*每输出5个数字就换行*/
cout << endl;
}
cout << endl;
}
/*数组初始化*/
void InitChooseArray(dataType arr[], int length)
{
srand((unsigned)time(NULL));/*设置随机数的种子*/
for (int i = 0; i < length; i++)
{
arr[i] = rand() % 100 + 1;/*数组为1~100的随机数*/
}
}
/*交换数字*/
void Swap(dataType *a, dataType *b)
{
dataType temp;
temp = *a;
*a = *b;
*b = temp;
}
/*选择排序*/
void ChooseSort(dataType arr[], int length)
{
int i, j;
for (i = 0; i < length-1; i++)
{
int min = i;/*记录最小的数的下标*/
for ( j = i + 1; j < length; j++)
{
if (arr[j] < arr[min])
min = j;
}
Swap(&arr[i], &arr[min]);
}
}
/*测试选择排序*/
void TestChooseSort()
{
int length;
cout << "输入你期望的数组长度:";
cin >> length;
dataType *arr = new dataType[length];
InitChooseArray(arr, length);
cout << "输出待排序的数组:" << endl;
PrintChooseArray(arr, length);
ChooseSort(arr,length);
cout << "输出排序后的数组:" << endl;
PrintChooseArray(arr, length);
delete[] arr;
}
主函数
#include <stdio.h>
#include "选择排序.h"
int main()
{
TestChooseSort();
getchar();
getchar();
return 0;
}
运行结果
参考网站以及博客:
百度百科https://baike.baidu.com/item/%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F/9762418?fr=aladdin