Reputation: 4295
I currently have an excel spreadsheet which contains many columns.
For example
Id Name Address Class School SchoolAddress
I would like to split the data into multiple sheets using a C# script where the Class School and School Address will be used as grouping. Similar to SQL GROUP BY
.
I currently have 2 for
loops.
(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
}
It is currently running in O(n^2) time which is too long. Does anyone have a faster solution?
Apologies. My question is actually on the logic efficiency rather than on the exact implementation of the code
Upvotes: 0
Views: 279
Reputation: 127
The name of your algorithm is BubbleSort, and is very slow. This is the quickSort Algorithm, one of the fastest sorter algorithms, its complexity is O(n log n). I use only this for sorting arrays.
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);
}
}
}
}
For more information about QuickSort you can look at this link: http://en.wikipedia.org/wiki/Quicksort
Upvotes: 2