1. 选择排序算法介绍
每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。选择排序是不稳定的排序方法。时间负责度为O(n^2)。
2. 算法实现
2.1 选择排序<由高到低>
//type * pArray: 待排序数组指针
//int len:数组的长度
//typename type:模板库
template <typename type>
void SelectSortHigh2Low(type * pArray, int len);
template <typename type>
void SelectSortHigh2Low(type * pArray, int len)
{
int i, j;
int temp;
for (i=0; i<len-1; i++)
{
temp = i;
for (j=i+1; j<len; j++)
{
if (pArray[temp]<pArray[j])
temp = j;
}
if (temp!=i)
Swap(&pArray[i], &pArray[temp]);
}
}
2.2 选择排序<由低到高>
//type * pArray: 待排序数组指针
//int len:数组的长度
//typename type:模板库
template <typename type>
void SelectSortlow2High(type * pArray, int len);
template <typename type>
void SelectSortlow2High(type * pArray, int len)
{
int i, j;
int temp;
for (i=0; i<len-1; i++)
{
temp = i;
for (j=i+1; j<len; j++)
{
if (pArray[temp]>pArray[j])
temp = j;
}
if (temp!=i)
Swap(&pArray[i], &pArray[temp]);
}
}
2.3 交换数值
template <typename type>
void Swap(type * lhs, type * rhs)
{
type temp = *lhs;
*lhs = *rhs;
*rhs = temp;
}
3. 示例
在主函数中输入10个等长的字符串(每个字符串最多10个字符),对他们进行由大到小的排序,然后再主函数进行输出结果。
输入
10个等长的字符串,用空格分隔。
输出
输出排序后的字符串
样例:
输入: she its can ibm bbc NBA nhk BOY jxf eat
输出: BOY NBA bbc can eat ibm its jxf nhk she
//数组定义:
void arrary[3][10];//连续型的数组定义
void SelectSortLow2High(char pArray[][10], int len)
{
int i, j;
int temp;
for (i=0; i<len-1; i++)
{
temp = i;
for (j=i+1; j<len; j++)
{
if ( memcmp(pArray[temp], pArray[j], strlen(pArray[j])) > 0 )
temp = j;
}
if (temp!=i)
Swap(pArray[i], pArray[temp]);
}
}
void Swap(char * lhs, char * rhs)
{
char temp[10] = {'\0'};
memcpy(temp, lhs, strlen(lhs));
memcpy(lhs, rhs, strlen(rhs));
memcpy(rhs, temp, strlen(temp));
}