在条件不限的情况下,如果要我对一个数组进行排序,我的首选肯定是选择排序,个人感觉这是最好理解的一种算法。
还是用扑克牌来打比方,左手上是一堆已经排好序的牌,右手上是一组乱序的牌。每次从右手选择最小的一张牌,追加到左手上。这个算法比插入排序好理解的地方在于,左手上的牌总是跟最终结果一致的,而不存在新的牌来了以后需要右移的情况。另外,从一组牌中选出一个最小的,我觉得也比冒泡排序不停的交换两个元素更容易理解。
#include <stdio.h>
#include "array_sort.h"
#include "base.h"
/**
* @brief Selection Sort for array.
*
* select the minium card from the unsorted cards in right hand,
* insert it into the end of the sorted cards in left hand.
*
* @note Complexity: O(n^2).
* @param array The array need to be sort.
* @param len Length of array.
* @return The sorted array.
*/
int *selection_sort (int *array, int len)
{
int i, j;
int *min;
/* Not necessary to check the last element */
for (i = 0; i < len - 1; i++)
{
min = &array[i];
for(j = i + 1; j < len; j++)
{
if (array[j] < *min)
{
min = &array[j];
}
}
swap (&array[i], min);
}
return array;
}