簡體   English   中英

使用左右邊界在C#中進行插入排序

[英]Insertion sort in C# using left and right boundaries

如何使用左右邊界來創建插入排序方法。

   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);
    }

使用左右邊界在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();
    }
}

插入排序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM