使用左右边界在C#中进行插入排序

时间:2015-09-02 11:13:34

标签: c# algorithm sorting generics insertion-sort

如何使用特定左右边界创建插入排序方法。

   public static void InsertionWorker<TYPE>(TYPE[] data, int left, int right) where TYPE : IComparable<TYPE>
    {
        TYPE temp;
        for (int firstSorted = 0; firstSorted < data.Length - 1; firstSorted++)

        for (int current = firstSorted + 1; current > 0; current--)
        {
          if (data[current - 1].CompareTo(data[current]) < 0)
          {
             temp = data[current - 1];
             data[current - 1] = data[current];
              data[current] = temp;
          }
          current--;
       }
    }

    public static void Insertion<TYPE>(TYPE[] data) where TYPE : IComparable<TYPE>
    {
        InsertionWorker(data, 0, data.Length - 1);
    }

1 个答案:

答案 0 :(得分:0)

使用左右边界在C#中实现Insertion sort

class Program
{
    public static void InsertionWorker<T>(T[] data, int left, int right) where T : IComparable<T>
    {
        for (var i = left; i < right + 1; i++)
        {
            T tmp = data[i];
            int j;
            for (j = i - 1; j >= left && tmp.CompareTo(data[j]) < 0; j--)
            {
                data[j + 1] = data[j];

            }
            data[j + 1] = tmp;
        }
    }

    static void Main(string[] args)
    {
        // test data array
        var a = new[] {234, 2, 11111, 34, 24, 23, 4, 432, 42, 423, 1, 4, 123, 124, 32, 345, 45, 3, 7, 56,9999999};

        // Run insertion sort by provided boundaries
        InsertionWorker(a, 7, a.Length-1);

        // InsertionWorker(a, 0, 8);

        foreach (int t in a)
        {
            Console.WriteLine(t);
        }
        Console.ReadKey();
    }
}

Insertion sort