(1)简单选择排序
头文件:
#define
MAXSIZE 20

#define
EQ(a, b) ((a) == (b))
#define
LT(a, b) ((a) < (b))
#define
LQ(a, b) ((a) <= (b))

typedef
int
KeyType;
typedef
int
InfoType;

typedef
struct
...
{
KeyType key;
InfoType otherinfo;
}
RedType;

typedef
struct
...
{
RedType r[MAXSIZE + 1];
int length;
}
SqList;
源文件:
#include
"
sort.h
"

#include
"
stdio.h
"


void
init(SqList
&
s,
int
w[],
int
n)
...
{
s.length = n;
for(int i = 1; i <= n; i++)...{
s.r[i].key = w[i - 1];
}
}


void
show(SqList s)
...
{
for(int i = 1; i <= s.length; i++)...{
printf("%d ", s.r[i]);
}
printf(" ");
}


int
selectMin(SqList
&
s,
int
i)
...
{
int key = s.r[i].key;
int ret = i;
for(int k = i; k <= s.length; k++)...{
if(key > s.r[k].key)...{
key = s.r[k].key;
ret = k;
}
}
return ret;
}


void
selectSort(SqList
&
s)
...
{
for(int i = 1; i <= s.length; i++)...{
int j = selectMin(s, i);
if(i != j)...{
RedType tmp = s.r[i];
s.r[i] = s.r[j];
s.r[j] = tmp;
}
}
}


void
main()
...
{
int w[] = ...{49, 38, 65, 97, 76, 13, 27, 49};
int n = 8;
SqList s;
init(s, w, n);
selectSort(s);
show(s);
}
程序运行结果:
13
27
38
49
49
65
76
97
Press any key to
continue
算法的复杂度为O(n * n),主要是关键字的比较。
(2)堆排序
头文件:
#define
MAXSIZE 20

#define
EQ(a, b) ((a) == (b))
#define
LT(a, b) ((a) < (b))
#define
LQ(a, b) ((a) <= (b))

typedef
int
KeyType;
typedef
int
InfoType;

typedef
struct
...
{
KeyType key;
InfoType otherinfo;
}
RedType;

typedef
struct
...
{
RedType r[MAXSIZE + 1];
int length;
}
HeapType;
源文件:
#include
"
sort.h
"
#include
"
stdio.h
"


void
init(HeapType
&
s,
int
w[],
int
n)
...
{
s.length = n;
for(int i = 1; i <= n; i++)...{
s.r[i].key = w[i - 1];
}
}


void
show(HeapType s)
...
{
for(int i = 1; i <= s.length; i++)...{
printf("%d ", s.r[i]);
}
printf(" ");
}

//
adjust the heap from s to m, to be a max heap.

void
heapAdjust(HeapType
&
h,
int
s,
int
m)
...
{
RedType rc = h.r[s];
for(int j = 2 * s; j <= m; j *= 2)...{
if(j < m && LT(h.r[j].key, h.r[j + 1].key))...{
j++;
}

if(!LT(rc.key, h.r[j].key))...{
break;
}
h.r[s] = h.r[j];
s = j;
}
h.r[s] = rc;
}


void
heapSort(HeapType
&
h)
...
{
//construct the heap
for(int i = h.length / 2; i > 0; i--)...{
heapAdjust(h, i, h.length);
}

for(i = h.length; i > 1; i--)...{
RedType rc = h.r[i];
h.r[i] = h.r[1];
h.r[1] = rc;
heapAdjust(h, 1, i - 1);
}
}


void
main()
...
{
int w[] = ...{49, 38, 65, 97, 76, 13, 27, 49};
int n = 8;
HeapType h;
init(h, w, n);
heapSort(h);
show(h);
}
程序执行结果:
13
27
38
49
49
65
76
97
Press any key to
continue
说明:
当n较小时,不值得用heapsort;最坏情况的复杂度为O(n * log(n))。

5888

被折叠的 条评论
为什么被折叠?



