数据结构 排序 交换排序

(1)冒泡排序

头文件:

#define MAXSIZE20

#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 ... {
KeyTypekey;
InfoTypeotherinfo;
}
RedType;

typedef
struct ... {
RedTyper[MAXSIZE
+1];
intlength;
}
SqList;

源文件:

#include " sort.h "

#include
" stdio.h "

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

}


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

printf(
" ");
}


void bubbleSort(SqList & s) ... {
intflag=1;
for(inti=s.length;i>=1&&flag;i--)...{
flag
=0;
for(intj=1;j<=i;j++)...{
if(LT(s.r[j].key,s.r[j-1].key))...{
RedTyperc
=s.r[j-1];
s.r[j
-1]=s.r[j];
s.r[j]
=rc;
flag
=1;
}

}

}

}


void main() ... {
intw[]=...{49,38,65,97,76,13,27,49};
intn=8;

SqLists;
init(s,w,n);

bubbleSort(s);
show(s);
}

程序执行结果:

13 27 38 49 49 65 76 97
Pressanykeyto
continue

程序的复杂度为:O(n * n)。

(2)快速排序

源文件修改:

// user[low]aspivottopartfromlowtohigh.
int partition(SqList & s, int low, int high) ... {
s.r[
0]=s.r[low];
KeyTypekey
=s.r[low].key;
while(low<high)...{
while(low<high&&s.r[high].key>=key)...{
high
--;
}

s.r[low]
=s.r[high];

while(low<high&&s.r[low].key<=key)...{
low
++;
}

s.r[high]
=s.r[0];
}


returnlow;
}


void qSort(SqList & s, int low, int high) ... {
if(low<high)...{
intpivot=partition(s,low,high);
qSort(s,low,pivot
-1);
qSort(s,pivot
+1,high);
}

}


void quickSort(SqList & s) ... {
qSort(s,
1,s.length);
}


void main() ... {
intw[]=...{49,38,65,97,76,13,27,49};
intn=8;

SqLists;
init(s,w,n);

quickSort(s);
show(s);
}

程序执行结果:

13 27 38 49 49 65 76 97
Pressanykeyto
continue

算法的复杂度为:平均O(n * log(n)),最坏O(n * n)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值