冒泡排序使用递归在C# [英] Bubble sort using recursion in C#

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

问题描述

我已经写了一段简单的代码。而且我有一个小问题与它

I've wrote this simple piece of code. And I have a slight problem with it.

int [] x = [50,70,10,12,129];
sort(x, 0,1);
sort(x, 1,2);
sort(x, 2,3);
sort(x, 3,4);

for(int i = 0; i < 5; i++) 
 Console.WriteLine(x[i]);

static int [] sort(int [] x, int i, int j)
{
   if(j ==x.length) 
      return x;
   else if(x[i]>x[j])
   {
      int temp = x[i];
      x[i] = x[j];
      x[j] = temp;
      return sort(x, i, j+1);
    }
    else 
       return sort(x, i, j+1);
}



我觉得打电话排序4时是不是最好的soultion。我需要一种方法来处理也采用这种排序()。我也要求你的忠告,建议或提示。
谢谢

I feel that calling sort 4 time isn't the best soultion. I need a way to handle this using sort() also. I also ask you for your advice, suggestion, or tip. Thanks

推荐答案

首先,你的排序限制为整数,但是你可以使用 IComparable的< T> 接口,将其扩展到任何类似的类型。或者你可以有一个的Comparer<另一个参数; T> 来允许用户定义如何比较在输入项目。

Firstly, your sort is restricted to ints, however you can use the IComparable<T> interface to extend it to any comparable type. Alternatively you could have another parameter for a Comparer<T> to allow the user to define how to compare items in the input.

一个递归冒泡排序可能会是这个样子:(注:未测试......)

A recursive bubble sort would probably look something like this: (NOTE: not tested...)

public static T[] BubbleSort(T[] input) where T : IComparable<T>
{
    return BubbleSort(input, 0, 0);
}

public static T[] BubbleSort(T[] input, int passStartIndex, int currentIndex) where T : IComparable<T>
{
    if(passStartIndex == input.Length - 1) return input;
    if(currentIndex == input.Length - 1) return BubbleSort(input, passStartIndex+1, passStartIndex+1);

    //compare items at current index and current index + 1 and swap if required
    int nextIndex = currentIndex + 1;
    if(input[currentIndex].CompareTo(input[nextIndex]) > 0)
    {
    	T temp = input[nextIndex];
    	input[nextIndex] = input[currentIndex];
    	input[currentIndex] = temp;
    }

    return BubbleSort(input, passStartIndex, currentIndex + 1);
}



不过,迭代求解很可能会更有效,更容易理解..

However, an iterative solution would probably be more efficient and easier to understand...

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

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