c语言任一数组排序,C语言一维数组排序

交换排序

1.冒泡排序

算法思想

1.将所有元素放入数组中;

2.从第一个元素开始,依次将相邻的两个元素比较,若前者大于后者则交换;

3.重复第2步,直到没有交换为止。

程序实现

void sort(int *a, int n)

{

int i, j, t, ok;

for(i=0; i

ok=1;

for(j=0; j

if(a[j]>a[j+1]){

t=a[j];

a[j]=a[j+1];

a[j+1]=t;

ok=0;

}

if(ok)

break;

}

}

void sort(int a[], int n)

{

int i, t, ok;

if(n==1)

reurn;

else{

for(i=0;i

if(a[i]>a[i+1]){

t=a[i];

a[i]=a[i+1];

a[i+1]=t;

ok=0;

}

if(ok)

return;

else

sort(a,n-1);

}

}

2.交换排序的另一种方法

void sort(int temp_array[ ],int n)

{

int i,j,t;

for(i=0;i

for(j=i+1;j

if(temp_array[i]> temp_array[j]){

t=temp_array[i];

temp_array[i]=temp_array[j];

temp_array[j]=t;

}

}

选择排序

算法思想

记住每趟比较中最小的数据下标,最后将最小元素与起始元素交换,这样每趟只交换一次。

程序实现

void sort(int temp_array[ ],int n)

{

int i,j,point,t;

for(i=0;i

point=i;

for(j=i+1;j

if(temp_array[point]> temp_array[j])

point=j;

if(point!=i){

t=temp_array[point];

temp_array[point]=temp_array[i];

temp_array [i]=t;

}

}

}

插入排序

算法思想

1.新建一个空列表,用于保存有序数列;

2.从原数列取出一个数插入有序列表中,使其仍保持有序状态;

3.重复第2步,直至原数列为空。

程序实现

void sort(int a[],int n)

{

int i,j,t;

for(i=1;i

t=a[i];              //第i+1个数

for(j=i-1;a[j]>t&&j>=0;j--)  //第j个数小于t或所有数都大于t

a[j+1]=a[j];         //大于t的数向后挪动

a[j+1]=t;             //将t插入第j+1位置

}

}

查找算法

线性查找法:时间复杂度O(n)级

for(i=0;i

if(x[i]==key) {

m=i;

break;

}

if(m!=-1)

printf(“found! %d”,m);

else

printf(“not found!”);

折半查找法:时间复杂度O(log2n)级

21604555a4c6158d677b6827f29b9c8c.png

while(low<=high){

mid=(low+high)/2;

if(a[mid]==key){

k=mid;

break;

}

if(key

high=mid-1;

else

low=mid+1;

}

int search(int x[ ],int low,int high,int key)

{

int mid;

mid=(low+high)/2;

if(x[mid]==key)

return mid;

if(low>=high)

return –1;

else if(key

return search(x,low,mid-1,key);

else

return search(x,mid+1,high,key);

}

标签:sort,ok,temp,int,void,C语言,一维,array,排序

来源: https://www.cnblogs.com/yuukirito/p/14776405.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值