2013-07-10 55 views
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)時間太長。有沒有人有更快的解決方案?

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

+0

感謝您抽出寶貴的邏輯效率考慮在內,但你的語法不正確。 – Raptor

+0

http://www.codeproject.com/Articles/31516/Export-DataSet-to-Multiple-Excel-Sheets –

回答

3

算法的名稱是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); 
      } 
     } 

    } 
} 

更多有關快速排序,你可以看看這個鏈接: http://en.wikipedia.org/wiki/Quicksort