簡體   English   中英

低效的數據排序算法

[英]Inefficient algorithm of sorting data

我目前有一個excel電子表格,其中包含許多列。

例如

Id  Name  Address  Class School SchoolAddress

我想使用C#腳本將數據拆分成多個表格,其中Class School和School Address將用作分組。 與SQL GROUP BY類似。

我目前有2個for循環。

(for int i = 1; i <= range.rows.count; i++)
{ 
   (for int a = 1; a <= range.rows.count; a++)

   //stores them in an array list and splits them
   //takes the Class school and school Address column to compare against
}

它目前在O(n ^ 2)時間內運行太長。 有沒有人有更快的解決方案?

道歉。 我的問題實際上是關於邏輯效率而不是代碼的確切實現

算法的名稱是BubbleSort,速度非常慢。 這是quickSort算法,是最快的分類算法之一,其復雜度為O(n log n)。 我只使用它來排序數組。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Quicksort
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an unsorted array of string elements
            string[] unsorted = { "z","e","x","c","m","q","a"};

            // Print the unsorted array
            for (int i = 0; i < unsorted.Length; i++)
            {
                Console.Write(unsorted[i] + " ");
            }

            Console.WriteLine();

            // Sort the array
            Quicksort(unsorted, 0, unsorted.Length - 1);

            // Print the sorted array
            for (int i = 0; i < unsorted.Length; i++)
            {
                Console.Write(unsorted[i] + " ");
            }

            Console.WriteLine();

            Console.ReadLine();
        }

        public static void Quicksort(IComparable[] elements, int left, int right)
        {
            int i = left, j = right;
            IComparable pivot = elements[(left + right) / 2];

            while (i <= j)
            {
                while (elements[i].CompareTo(pivot) < 0)
                {
                    i++;
                }

                while (elements[j].CompareTo(pivot) > 0)
                {
                    j--;
                }

                if (i <= j)
                {
                    // Swap
                    IComparable tmp = elements[i];
                    elements[i] = elements[j];
                    elements[j] = tmp;

                    i++;
                    j--;
                }
            }

            // Recursive calls
            if (left < j)
            {
                Quicksort(elements, left, j);
            }

            if (i < right)
            {
                Quicksort(elements, i, right);
            }
        }

    }
}

有關QuickSort的更多信息,您可以查看以下鏈接: http//en.wikipedia.org/wiki/Quicksort

暫無
暫無

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

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