C#C
C#10mo ago
springblitz

QuickSort implementation gets me an out-of-range error

I'm having some trouble with a quick sort function. Although I checked to make sure the bounds were the correct numbers when calling the method, I still get a System.ArgumentOutOfRangeException error message upon execution. Is there something within the method itself that causes it to go out of range? Or did I perhaps miss something silly?
Below is a snippet of my code:
C#
    static int MakePivot(List<int> mylist, int left, int right){ //for quick sort.
        int pivot = mylist[right]; //pivot on the right
        int cursor = mylist[left] - 1;
        for(int i=left;i<right;i++){
            if(mylist[i]<=pivot){
                cursor++;
                (mylist[cursor], mylist[i]) = (mylist[i], mylist[cursor]);
            }
        }
        pivot = cursor + 1;
        (mylist[pivot], mylist[right]) = (mylist[right], mylist[pivot]);
        return pivot;
    }
    static void QuickSort(List<int> mylist, int left, int right){
        if(left<right){
            int pivot = MakePivot(mylist,left,right);
            QuickSort(mylist,left,pivot-1);
            QuickSort(mylist,pivot+1,right);
        }
    }
    static void Main(string[] args){
        List<int>x = MakeList("7,4,8,9,5,3,2,6"); //MakeList() takes a string of single digits and returns an integer list. Works fine.
        Console.WriteLine("Before QS: ");
        for(int i=0;i<x.Count;i++){
            Console.Write("{0} ",x[i]);
        }
        QuickSort(x,0,x.Count-1);
        Console.WriteLine("After QS: ");
        for(int i=0;i<x.Count;i++){
            Console.Write("{0} ",x[i]);
        }
        Console.WriteLine("");
    }
image.png
Was this page helpful?