简体   繁体   English

通用快速排序算法

[英]Generic Quick sorting algorithm

I am very new to this site and also a beginner programmer. 我是这个网站的新手,也是一名初学者。 I have been given a quick sort method which will sort an array of generic objects. 我获得了一种快速排序方法,该方法将对通用对象数组进行排序。 I am using the in built compareTo method but when i come to call my method, it wont compile. 我正在使用内置的compareTo方法,但是当我调用我的方法时,它将无法编译。 The quicksort method takes an array of T items and an int left and int right. quicksort方法采用T项的数组以及int左和int右。 I do not know how to call on my method and when i do get it to work, my array doesnt become sorted. 我不知道如何调用我的方法,当我确实使它工作时,我的数组没有被排序。 Can anyone give me any help at all? 谁能给我任何帮助? Im really struggling to understand and most sites on the internet are slightly to complex for my knowledge :( Heres the code: 我真的很难理解,据我所知,Internet上的大多数站点都有些复杂:(以下是代码:

    namespace QuickSort2
   {
    class Program
    {
     private void QuickSort<T>(T[] items, int left,  int right) where T: IComparable
     {
        int i, j;
        i = left; j = right;
        IComparable pivot = items[left];

        while (i <= j)
        {
            for (; (items[i].CompareTo(pivot) < 0) && (i.CompareTo(right) < 0); i++); 
            for (; (pivot.CompareTo(items[j]) < 0) && (j.CompareTo(left) > 0); j--); 

             if (i <= j) 
            swap(ref items[i++], ref items[j--]); 

        } 
             if (left < j) QuickSort<T>(items, left,  j); 
             if (i < right) QuickSort<T>(items, i, right); 
    }
     static void swap<T>(ref T x, ref T y)
    {
      //swapcount++;
        T temp = x;
        x = y;
        y = temp;
    }

    static void Main(string[] args)
    {
        IComparable[] array1 = { 3,5,7,8,1,2 };


        foreach (int s in array1)
        {
            Console.WriteLine(" {0} ", s);
        }

        Console.ReadKey();
        Console.WriteLine("Sorted version");
        foreach (int x in array1)
        {
            QuickSort(array1, 0, array1.Length - 1);
            Console.WriteLine(" {0} ", x);
        }
        Console.ReadKey();
    }


    }
   }

Your code is fine, but you're not actually calling the QuickSort method... (EDIT: not true anymore after you edited your question...) 您的代码很好, 但是您实际上并没有调用 QuickSort方法... (编辑:编辑问题后不再是真的...)

QuickSort(array1, 0, array1.Length - 1);

You also need to make the QuickSort method static to be able to call it from the static method Main . 您还需要使QuickSort方法成为静态方法,以便能够从静态方法Main调用它。

private static void QuickSort<T>(T[] items, int left,  int right) where T: IComparable

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

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