直接选择排序
算法思想
见:3. 选择排序—简单选择排序(Simple Selection Sort)
程序
数组实现
void swap(int *s1, int *s2)
{
int tem;
tem = *s2;
*s2 = *s1;
*s1 = tem;
}
void SelectSort(int a[], int n)
{
int i, j, max;
for (i = 0; i < n-1; i++) {
max = i;
for (j = i+1; j < n; j++)
if (a[j] > a[max])
max = j;//记录大的下标
swap(&a[max],&a[i]);
}
}
时间复杂度:
链表实现
struct node;
typedef struct node *ptrtonode;
typedef ptrtonode list;
typedef ptrtonode position;
struct node {
int data;
ptrtonode next;
};
void SwapNode(position p, position q)
{
int n;
n = p->data;
p->data = q->data;
q->data = n;
}
void SelectSort(list L)
{
position p = L, pmax, ptemp;
while (p->next != NULL) {
pmax = p->next;
ptemp = pmax->next;
while (ptemp != NULL) {
if (ptemp->data > pmax->data)
pmax = ptem;
ptemp = ptemp->next;
}
p = p->next;
SwapNode(p, pmax);
}
}
二元选择排序
算法思想
程序
//从大到小排序,减少循环次数
void BSelectSort(int a[], int n)
{
int i, j, min, max;
for (i = 0; i < n/2; i++) {
min = i, max = i;
for (j = i+1; j < n-i; j++) {
if (a[j] > a[max]) {
max = j;
continue;
}
if (a[j] < a[min])
min = j;
}
swap(&a[i],&a[max]);
swap(&a[n-i-1],&a[min]);
}
}
来源:CSDN
作者:cd-qz
链接:https://blog.csdn.net/Lee567/article/details/103667660