Bubble sort using recursion in C#

前端 未结 4 715
生来不讨喜
生来不讨喜 2020-12-20 01:09

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条回答
  •  北海茫月
    2020-12-20 01:54

    Firstly, your sort is restricted to ints, however you can use the IComparable interface to extend it to any comparable type. Alternatively you could have another parameter for a Comparer 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
    {
        return BubbleSort(input, 0, 0);
    }
    
    public static T[] BubbleSort(T[] input, int passStartIndex, int currentIndex) where T : IComparable
    {
        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...

提交回复
热议问题