繁体   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