0

我目前有一个包含许多列的 excel 电子表格。

例如

Id  Name  Address  Class School SchoolAddress

我想使用 C# 脚本将数据拆分为多个工作表,其中班级学校和学校地址将用作分组。类似于 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) 时间内运行,时间太长。有没有人有更快的解决方案?

道歉。我的问题实际上是关于逻辑效率而不是代码的确切实现

4

1 回答 1

2

您的算法的名称是 BubbleSort,而且非常慢。这是快速排序算法,最快的排序算法之一,其复杂度为 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

于 2013-07-10T08:22:42.553 回答