选择排序描述
选择排序开始的时候,扫描整个列表,找到它的最小元素然后和第一个元素交换,将最小元素放到它在有序表中的最终位置上。然后我们从第二个元素开始扫描列表,找到最后n-1个元素中的最小元素,再和第二个元素交换位置,把第二小的元素放到它在有序表中的最终位置上。一般来说,在对该列表做第 i 遍扫描的时候(i 的值从0到n-2),该算法在最后n-1个元素中寻找最小元素,然后拿它和A[i]交换:
在n-1遍以后,该列表就被排好序了。
算法:
SelectionSort(A[0...n-1])
//该算法用选择排序对给定的数组排序
//输入:一个可排序的数组A[0...n-1]
//输出:非降序排列的数组A[0...n-1]
for i <- 0 to i <- n-2 do
min <- i
for j <- i+1 to j <- n-1 do
if A[j] < A[min] min <- j
swap A[i] and A[min]
选择排序的实现
// SelectionSort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "typedef.h"
/*
*函数名:Compare_uint
*参数:pKey1 指向第一个比较元素的地址
* pKey2 指向第二个比较元素的地址
*功能:比较两个元素的大小
*返回值:1 表示Key1 大于 Key2
* -1 表示Key1 小于 Key2
* 0 表示Key1 等于 Key2
*作者:AlbertoNo1
*日期:2016-03-15
*/
INT32 Compare_uint(VOID *pKey1, VOID *pKey2)
{
/*对两个无符号整型数进行比较*/
if (*((UINT32*)pKey1) > *((UINT32*)pKey2))
{
return 1;
}
else if (*((UINT32*)pKey1) < *((UINT32*)pKey2))
{
return -1;
}
else
{
return 0;
}
}
/*
*函数名:Swap
*参数:pKey1 指向第一个交换元素的地址
* pKey2 指向第二个交换元素的地址
* uiKeySize 交换元素所占内存大小(Byte)
*功能:交换两个元素的位置
*返回值:无
*作者:AlbertoNo1
*日期:2016-03-15
*/
VOID Swap(VOID *pKey1, VOID *pKey2, UINT32 uiKeySize)
{
VOID *pTemp = NULL;
if (NULL == (pTemp = malloc(uiKeySize)))
{
return;
}
memcpy(pTemp, pKey1, uiKeySize);
memcpy(pKey1, pKey2, uiKeySize);
memcpy(pKey2, pTemp, uiKeySize);
}
/*
*函数名:SelectionSort
*参数:pData 待排序数组数据的首地址
* uiSize 数据的元素个数
* uiElmSize 数据元素所占内存大小(Byte)
* compare 两个元素的比较函数
*功能:对数组进行选择排序
*返回值:无
*作者:AlbertoNo1
*日期:2016-03-21
*/
VOID SelectionSort(VOID *pData, UINT32 uiSize, UINT32 uiElmSize, INT32 (*compare)(VOID *pKey1, VOID *pKey2))
{
UINT32 i = 0;
UINT32 j = 0;
UINT32 uiSwitchPos = 0; /*存储一轮比较最终要交换的位置*/
CHAR *pucData = NULL;
if (uiSize <= 1)
{/*不用排序*/
return ;
}
pucData = (CHAR*)pData;
for (i = 0; i < uiSize -1; i++)
{/*进过 uiSzie-1 轮比较后,排序完成*/
uiSwitchPos = i;
for (j = i+1; j < uiSize; j++)
{
if (compare(&pucData[j*uiElmSize], &pucData[uiSwitchPos*uiElmSize])<0)
{
uiSwitchPos = j;
}
}
if (i != uiSwitchPos)
{
Swap(&pucData[i*uiElmSize], &pucData[uiSwitchPos*uiElmSize], uiElmSize);
}
}
return ;
}
int _tmain(int argc, _TCHAR* argv[])
{
INT32 iRet = 0;
UINT32 uiLoop = 0;
//UINT32 auiData[] = {10,15,15,18,20,20,20,36,48,51,51,77,77};
//UINT32 auiData[] = {77,77,51,51,48,36,20,20,20,18,15,15,10};
UINT32 auiData[] = {77,15,20,18,51,51,36,10,77,15,20,20,48};
//UINT32 auiData[] = {77,77};
//UINT32 auiData[] = {77};
SelectionSort(auiData, sizeof(auiData)/sizeof(auiData[0]), sizeof(auiData[0]),Compare_uint);
printf("Selection Sort Success.\n");
printf("Result:\n");
for (uiLoop = 0; uiLoop < sizeof(auiData)/sizeof(auiData[0]); uiLoop++)
{
printf("%d ", auiData[uiLoop]);
}
getchar();
return 0;
}