排序

参考程序代码段:


#include <stdio.h>  
#include <stdlib.h>  
#include <time.h> 
#define N 10  //最大排序数据项个数

typedef struct{
	int r[N+1];
	int length;
}SqList;

//直接插入排序
void insertion(SqList &L) { 
	int i,j;
	for (i=2; i<=L.length; i++)
	{
		if(L.r[i]<L.r[i-1])
		{
			L.r[0]=L.r[i];
			L.r[i]=L.r[i-1];
			for (j=i-2; L.r[0]<L.r[j];j--)
				L.r[j+1]=L.r[j];
			L.r[j+1]=L.r[0];
		}
	}
}
//直接选择排序
void selection (SqList &L) {
	int i, j, min;
	for (i=1; i<L.length; i++) {
		min = i; 
		for (j = i+1; j <=L.length; j++)  
			if (L.r[j]<L.r[min] ) min=j;		
			if(i!=min) {L.r[0]=L.r[i];  L.r[i]=L.r[min];  L.r[min]=L.r[0];}
	}
}
//冒泡排序1
void bubble1(SqList &L) {
	int i,j;
	for (i=1; i<L.length; i++) {
		for (j=1; j<=L.length-i; j++)
			if(L.r[j]>L.r[j+1]) {L.r[0]=L.r[j];  L.r[j]=L.r[j+1];  L.r[j+1]=L.r[0];}
	}
}
//冒泡排序2
void bubble2(SqList &L) {
	int i,j,Exchange;
	for (i=1; i<L.length; i++) {
		Exchange=0;
		for (j=1; j<=L.length-i; j++)
			if(L.r[j]>L.r[j+1]) {L.r[0]=L.r[j];  L.r[j]=L.r[j+1];  L.r[j+1]=L.r[0];  Exchange=1;}
		if (Exchange==0) return;  //如果某趟冒泡排序中没有元素交换,则表明已整体有序
	}
}

void main(void) {
	SqList L;
	int i;
	srand(time(0));//用系统时间作为随机数种子
	for (i=1; i<=N; i++)
		L.r[i]=1000*rand()/RAND_MAX; //0-1000以内的随机整数
	L.length=N;
	printf(“排序前序列:”);
for (i=1; i<=L.length; i++) printf("%5d", L.r[i]);  //输出排序前的数列
	printf("\n");
	//以下由学生写入排序算法的调用代码
	//......
	//以上由学生写入排序算法的调用代码
	printf(“排序后序列:”);
for (i=1; i<=L.length; i++) printf("%5d", L.r[i]); //输出排序后的数列
	printf("\n");
}


主函数:

测试直接插入、直接选择和冒泡的排序算法:

selection(L);//直接插入
selection(L);//直接选择
bubble1(L);//冒泡排序


修改上面的直接插入、直接选择和冒泡的排序算法,使之能够显示每一趟的排序结果;
实验代码:

printf("第%d趟排序后为: ",i-2);	
for(int j=1;j<=L.length ;j++)
{
printf("%d ",L.r[j]);	
}
printf("\n");


实现快速排序的递归算法:


int partition(SqList &L, int low, int high)  
{  
L.r [0]=L.r[low];
   	int privotKey = L.r[low];                             
  	 while(low < high){                                     
       while(low < high  && L.r[high] >= privotKey) --high;  
       L.r[low]= L.r[high];  
       while(low < high  && L.r[low] <= privotKey ) ++low;  
       L.r[high]= L.r[low];  
    }  
   	L.r[low]= L.r[0];  
    return low;  
}  
  
void Qsort(SqList &L, int low, int high){  
    if(low < high){  
       	int privotLoc = partition(L,  low,  high);   
        Qsort(L,  low,  privotLoc -1);          
        Qsort(L,   privotLoc + 1, high);        
   }  
}  









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值