#include
<stdio.h>
#define
MAXSIZE
10
//
待排顺序表最大长度
typedef
int
KeyType
//
关键字类型为整数类型
typedef
struct
sqlist
{
KeyType
r[MAXSIZE+1]
//
r[0]闲置
int
length
//
顺序表长度
}SqList
//建立顺序表//
SqList
InputSList()
{int
xSqList
L
L.length=0
printf("\n请输入数据,结束输入-1!\n")
scanf("%d",&x)
while(x!=-1)
{
L.r[++L.length]=x
if(L.length==MAXSIZE)
{
printf("\n顺序表已满!\n")
break
}
scanf("%d",&x)
}
return
L
}
//直接插入排序//
void
InsertionSort
(SqList
*L
)
{
//
对顺序表
L
作直接插入排序。
int
i,j
SqList
*p=L
for
(
i=2
i<=p->length
++i
)
if
(p->r[i]
<
p->r[i-1])
{
p->r[0]
=
p->r[i]
p->r[i]=p->r[i-1]
for
(
j=i-2
p->r[0]
<
p->r[j]
--
j
)
p->r[j+1]
=
p->r[j]
//
记录后移
p->r[j+1]
=
p->r[0]
//
插入到正确位置
}
}
//冒泡排序//
void
BubbleSort(SqList
*L)
{
int
i,j,t
SqList
*p=L
for
(i=p->lengthi>1--i){
for
(j=1j<i++j)
if
(p->r[j+1]<p->r[j]){
t=p->r[j+1]
p->r[j+1]=p->r[j]
p->r[j]=t
}
}
}
//简单选择排序//
void
SelectSort
(SqList
*L
)
{
SqList
*p=L
int
i,
j,
k
KeyType
temp
for
(i=1
i<p->length
++i)
{
k=i
for
(j=i+1
j<=p->length
j++)
if
(p->r[j]<p->r
[k])
k=j
if
(k!=i)
{temp=p->r
[i]
p->r
[i]=p->r
[k]
p->r
[k]=temp
}
}
}
void
display(SqList
*L)
{
SqList
*p
p=L
if
(p->length!=0)
{
while(p->length)
{
printf("%d
",p->r[p->length])
p->length--
}
}
printf("\n")
}
void
main()
{
SqList
L
L=InputSList()
InsertionSort
(&L)
//
SelectSort
(&L)
//
BubbleSort(&L)
display(&L)
}
void InsertSort(sq R)这个函数是按值传递参数的。换句话说,你的顺序表在传递的时候被复制了一遍,然后这个函数收到的是一个副本,然后这个程序也许成功排序了这个副本,但是你原来的顺序表并没有改变。你可以考虑传递这个顺序表的指针。比如这样
void InsertSort(sq *pR){
sq R = *pR
//以下不变
...
}
调用的时候传递R的地址
InsertSort(&R)