簡體   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