怎么样使用递归的方法实现选择排序???救我!!!

eleven1012 2003-08-23 08:25:34
怎么样使用递归的方法实现选择排序???
是否所有的迭代都能用递归来实现??
谢谢高手们!!
...全文
352 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Dragon132 2003-08-23
  • 打赏
  • 举报
回复
选择排序的递归算法

#include <stdio.h>

select(int a[8],int m,int n)
{
int i,t,k;
k=m;
for(i=m+1;i<n;i++)
if(a[k]>a[i])
k=i;
if(k!=m)
{
t=a[k];
a[k]=a[m];
a[m]=t;
}
if(m<n)
select(a,m+1,n);
}

main()
{
int a[10]={46,55,13,42,94,17,05,70};
int i;
select(a,0,8);
for(i=0;i<8;i++)
printf("%4d",a[i]);
printf("\n");
}
sakurar 2003-08-23
  • 打赏
  • 举报
回复
快速排序、堆排序等树型排序都用递归方式,效率一点儿也不差。
liuyuw 2003-08-23
  • 打赏
  • 举报
回复
那不好说,可能有些能用,只是还没想出来而已,也可能有些根本就不能用递归。递归实现起来比较清楚,但是效率可能比有些实现要差一些。
eleven1012 2003-08-23
  • 打赏
  • 举报
回复
是否所有的迭代都能用递归来实现??
liuyuw 2003-08-23
  • 打赏
  • 举报
回复
很多啊,比如快速排序:

#include<iostream>
using namespace std;

void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}

int Partition(int a[],int low,int high)
{
int pivot=a[low];
while(low<high)
{
while(low<high&&a[high]>=pivot) --high;
swap(a[low],a[high]);
while(low<high&&a[low]<=pivot) ++low;
swap(a[high],a[low]);
}
return low;
}

void QSort(int a[],int low,int high)
{
if(low<high)
{
int pivotloc=Partition(a,low,high);
QSort(a,low,pivotloc-1);
QSort(a,pivotloc+1,high);
}
}


void main()
{
int a[10]={9,8,7,6,5,4,3,2,1,0};
QSort(a,0,10);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧