第1个回答 2013-09-21
选择法排序是一种简单的容易实现的对数据排序的算法。
以整形数组元素为例,有数组A[10](以C语言为例描述),即A[0],A[1],…,A[8],A[9](假设其元素均互不相同)。要求对其元素排序使之递增有序。
算法原理:首先以一个元素为基准,从一个方向开始扫描,比如从左至右扫描,以A[0]为基准。接下来从A[0],…,A[9]中找出最小的元素,将其与A[0]交换。然后将基准位置右移一位,重复上面的动作,比如,以A[1]为基准,找出A[1]~A[9]中最小的,将其与A[1]交换。一直进行到基准位置移到数组最后一个元素时排序结束(此时基准左边所有元素均递增有序,而基准为最后一个元素,故完成排序)。
以下为一个用C描述的函数实现上述排序:
void sort(int array[],int n) // n 为数组元素个数
{
int i,j,k,temp; // i 为基准位置,j 为当前被扫描元素位置,k 用于暂存出现的较小的元素的位置
for(i=0;i<n-1;i++)
{
k=i; // k 初始化为基准位置
for(j=i+1;j<n;j++)
if (array[j]<array[k]) k=j ; // k 始终指示出现的较小的元素的位置
temp=array[k];array[k]=array;array=temp; // 将此趟扫描得到的最小元素与基准互换位置
}
}
此算法的实现相对简单,但效率比较低,时间复杂度为O(n2) (n 的平方),为就地排序。
递归法比较好理解``
计算1+2+....+100的值
#include <stdio.h>
main()
{
printf("%d\n",fun(100));//调用函数fun()
}
递归函数
fun(int n)
{int t; <br/>if(n==0||n==1) t=1; //如果n为0或为1 输出1 <br/>//n大于0,则为第n项和第n-1项的和,继续调用fun() <br/>//以此类推... <br/>else t=n+fun(n-1); <br/>return t; <br/>}
#include <stdio.h>
main()
{printf("%d\n",fun(100));}
fun(int n)
{int t; <br/>if(n==0||n==1) t=1; <br/>else t=n+fun(n-1); <br/>return t; <br/>}
第2个回答 2013-09-21
计算1+2+....+100的值
#include <stdio.h>
main()
{
printf("%d\n",fun(100));//调用函数fun()
}
递归函数
fun(int n)
{int t; <br/>if(n==0||n==1) t=1; //如果n为0或为1 输出1 <br/>//n大于0,则为第n项和第n-1项的和,继续调用fun() <br/>//以此类推... <br/>else t=n+fun(n-1); <br/>return t; <br/>}
什么叫快速排序 qsort
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
struct student{
int xuehao;
char name[20];
int chengji;
};
typedef struct student stu;
sortbyxuehao(const void *,const void *);
sortbyname(const void *,const void *);
sortbychengji(const void *,const void *);
void main()
{
int i;
stu a[3];
int choice;
int (*p)(const void * ,const void *);
printf("please input record:\n");
printf("xuehao name chengji:\n");
for(i=0;i<3;i++)
{
scanf("%d",&a[i].xuehao);
scanf("%s",a[i].name);
scanf("%d",&a[i].chengji);
}
printf("choice_1: sorted xuehao:\n");
printf("choice_2: sorted name\n");
printf("choice_3: sorted chengji\n");
scanf("%d",&choice);
while(choice!=0)
{
if(choice==1)
p=sortbyxuehao;
if(choice==2)
p=sortbyname;
if(choice==3)
p=sortbychengji;
qsort(a,3,sizeof(stu),p);
if(choice==1)
for(i=0;i<3;i++)
printf("\n%d\t%s\t%d",a[i].xuehao,a[i].name,a[i].chengji);
if(choice==2)
for(i=0;i<3;i++)
printf("\n%s\t%d\t%d",a[i].name,a[i].xuehao,a[i].chengji);
if(choice==3)
for(i=0;i<3;i++)
printf("\n%d\t%s\t%d",a[i].chengji,a[i].name,a[i].xuehao);
printf("\n");
scanf("%d",&choice);
}
}
sortbyxuehao(const void *p,const void *q)
{
stu *x,*y;
x=(stu*)p;
y=(stu*)q;
return (-((*x).xuehao-(*y).xuehao));
}
sortbyname(const void *p,const void *q)
{
stu *x,*y;
x=(stu*)p;
y=(stu*)q;
return strcmp((*x).name,(*y).name);
}
sortbychengji(const void *p,const void *q)
{
stu *x,*y;
x=(stu*)p;
y=(stu*)q;
return ((*x).chengji-(*y).chengji);
}