Bubble sort using recursion in C#

前端 未结 4 717
生来不讨喜
生来不讨喜 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:43

    another one with only 2 params :p yeah :

    static void Sort(IList data)
    {
        Sort(data, 0);
    }
    
    static void Sort(IList 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);
    }
    

    Note : This is completly useless in real life because - its extremely slow - its recursion iteration is linear meaning that when you have more than 1k items, it will stackoverflow

提交回复
热议问题