选择排序
视频链接:https://live.csdn.net/v/234310
算法
选择排序(Selection-sort)是一种简单直观的排序算法。
它的工作原理:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,
然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕
手动推算
代码实现
#include <stdio.h>
bool SelectSort(int *array, int size)
{
//检查参数是否有效
if (array == NULL || size == 0)
{
return false;
}
//开始排序
int minIndex = 0;//记录每次比较的最小索引
int tempValue = 0;//临时存放需要交换的值
for (int index=0;index< size;index++)
{
//从当前已经排序好的后面开始找最小的值
minIndex = index;
for (int indexBack= minIndex+1;indexBack<size;indexBack++)
{
//和当前最小的索引比较值
if (array[indexBack]< array[minIndex])
{
minIndex = indexBack;
}
}
//交换最小值
tempValue = array[index];
array[index] = array[minIndex];
array[minIndex] = tempValue;
}
return true;
}
void PrintfArray(int *array, int size)
{
printf("=============================\n");
for (int index=0;index<size;index++)
{
printf("%d ", array[index]);
}
printf("\n");
}
int main()
{
int array[12] = { 2,5,7,45,33,6,72,1,12,8,3,0 };
PrintfArray(array, 12);
SelectSort(array, 12);
PrintfArray(array, 12);
printf("Hello Heart");
return 0;
}
文章评论