编写递归冒泡排序和选择排序C. [英] writing a recursive bubble sort and selection sort C

查看:168
本文介绍了编写递归冒泡排序和选择排序C.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想编写一个带递归函数的程序来排序数组(不使用for或while循环)



我试过不同的方法但是他们似乎有非常奇怪的错误





例如我想在选择中使用它

< pre lang =text> int find_max(int * array,int max,int i){
if(i> = 0){
if(array [i]> array [max]) find_min(数组,I,I-1);
find_max(array,max,i-1);

}
返回最大值;
}





但它会返回你发送的最大价值,一开始它不会改变

(我的编译器可能有问题吗?我使用mingw gcc)

解决方案

你永远不会改变max的值,但是你将它返回。



  int  find_max( int  *  array  int  max, int  i){
int localMax = -INT_MAX; // 初始值
如果(i> = 0 ){
if array [i]> array [max])find_min( array ,i,i- 1 );
find_min( array ,max,i- 1 );
// TODO:实现你的作业
// localMax = ????

}
返回 localMax;
}


不,你的逻辑有问题。

看看你的代码:我会缩进它更清楚一点,所以它更明显。

  int  find_max( int  *  array  int  max, int  i)
{
if (i> = 0
{
if array [i]> array [ max])
{
find_min( array ,i,i- 1 ) ;
}
find_min( array ,max,i- 1 );
}
返回 max;
}

这里有两点需要注意:

1)它不是递归的,或者至少不是直接的。递归意味着从方法内(或在它调用的方法中)调用相同的方法。除非find_min调用find_max,否则这里没有递归。

2)你的方法总是返回相同的值 - 传入的最大值。无论find_min做什么都没关系,因为你总是忽略结果。



我建议您需要退一步,自己做一杯咖啡,并在完成后重新开始锻炼! :笑:


Hi I want to write a program with recursive function to sort an array (without using for or while loops)

I tried different ways but they seem to have very weird bugs


For example i wanted to use this in selection sort

int find_max(int *array,int max,int i){ 
if (i>=0){ 
		if (array[i]>array[max]) find_min(array,i,i-1);
		find_max(array,max,i-1);
		
	}
		return max;
}



But it will return whatever value you sent as max at first it wont change
(can there be a problem with my compiler ? i use mingw gcc)

解决方案

you never change the value of max, but you return it.

int find_max(int *array,int max,int i){ 
int localMax = -INT_MAX;//initial value
if (i>=0){ 
		if (array[i]>array[max]) find_min(array,i,i-1);
		find_min(array,max,i-1);
		//TODO: implement your homework
		//localMax = ????
	
	}
		return localMax ;
}


No, there is a problem with your logic.
Look at your code: I'll indent it a bit more clearly so it's more obvious.

int find_max(int *array,int max,int i)
   { 
   if (i>=0)
      { 
      if (array[i]>array[max]) 
          {
          find_min(array,i,i-1);
          }
      find_min(array,max,i-1);
      }
   return max;
   }

There are two things to note here:
1) It isn't recursive, or at least not directly. Recursion means calling the same method from within the method (or in a method it calls). Unless find_min calls find_max, there is no recursion here.
2) Your method always returns the same value - the max that was passed in. it doesn't matter what find_min does, because you always ignore the result.

I'd suggest that you need to take a couple of steps back, make yourself a coffee and start the exercise again when you have finished it! :laugh:


这篇关于编写递归冒泡排序和选择排序C.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆