繁体   English   中英

在C#中使用递归的冒泡排序

[英]Bubble sort using recursion in C#

我写了这段简单的代码。 我有一个小问题。

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次拜拜不是最好的灵魂。 我还需要一种方法来处理这个使用sort()。 我也问你的意见,建议或提示。 谢谢

一个简单的bubblesort不应该需要递归。 你可以这样做,只需传入数组进行排序:

public int[] Sort(int[] sortArray)
    {
        for (int i = 0; i < sortArray.Length - 1; i++)
        {
            for (int j = sortArray.Length - 1; j > i; j--)
            {
                if (sortArray[j] < sortArray[j - 1])
                {
                    int x = sortArray[j];
                    sortArray[j] = sortArray[j - 1];
                    sortArray[j - 1] = x;

                }
            }
        }
        return sortArray;
    } 

首先,您的排序仅限于int,但您可以使用IComparable<T>接口将其扩展为任何类似的类型。 或者,您可以为Comparer<T>提供另一个参数,以允许用户定义如何比较输入中的项目。

递归冒泡排序可能看起来像这样:(注意:未经测试......)

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);
}

但是,迭代解决方案可能更有效,更容易理解......

想要学习没什么不对 - 几件显而易见的事情。

首先你已经意识到数组有一个长度属性 - 所以你可以使用它来创建一个循环来摆脱多次调用以在开始时排序并使数组的长度成为一个非问题。

其次,您可能想要考虑排序的工作方式 - 这是怎么回事:您试图将值冒泡到列表中的正确位置(如果您愿意,可以向下!) - 所以对于n个项目的列表,删除第一个,排序剩余的n - 1个项目(这是递归位),然后将第一个项目冒泡到位。

自从我想到这几十年以来,好玩!

另一个只有2个参数:p是的:

static void Sort(IList<int> data)
{
    Sort(data, 0);
}

static void Sort(IList<int> data, int startIndex)
{
    if (startIndex >= data.Count) return;

    //find the index of the min value
    int minIndex = startIndex;
    for (int i = startIndex; i < data.Count; i++)
        if (data[i] < data[minIndex])
            minIndex = i;

    //exchange the values
    if (minIndex != startIndex)
    {
        var temp = data[startIndex];
        data[startIndex] = data[minIndex];
        data[minIndex] = temp;
    }

    //recurring to the next
    Sort(data, startIndex + 1);
}

注意:这在现实生活中是完全无用的,因为 - 它非常慢 - 它的递归迭代是线性的,这意味着当你有超过1k项时,它会堆栈溢出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM