I wrote a stable sort algorithm in C#. It is just a simple iteration, and is probably not very optimal:
static void StableSort(ref ObservableCollection<string> Vals, ref ObservableCollection<int> Weight)
{
for (int i = 0; i < Vals.Count; i++)
{
int LargestVal = -1;
int LargestValIndex = 0;
for (int j = i; j < Vals.Count; j++)
{
if (Weight[j] > LargestVal)
{
LargestVal = Weight[j];
LargestValIndex = j;
}
}
if (LargestValIndex != i)
{
Weight.Insert(i, Weight[LargestValIndex]);
Weight.RemoveAt(LargestValIndex + 1);
Vals.Insert(i, Vals[LargestValIndex]);
Vals.RemoveAt(LargestValIndex + 1);
}
}
}
You can see how it works by running it with this code (this isn't what I want a review on, but if you see something really wrong, please tell me):
static void Main(string[] args)
{
ObservableCollection<int> i = new ObservableCollection<int>() { 1, 2, 4, 6, 7, 2, 4, 7, 3, 3, 7 };
ObservableCollection<string> s = new ObservableCollection<string>() { "1", "2a", "4a", "6", "7a", "2b", "4b", "7b", "3a", "3b", "7c" };
foreach (int item in i)
{
Console.Write(item + ", ");
}
Console.WriteLine();
foreach (string item in s)
{
Console.Write(item + ", ");
}
Console.WriteLine();
StableSort(ref s, ref i);
Console.WriteLine();
foreach (int item in i)
{
Console.Write(item + ", ");
}
Console.WriteLine();
foreach (string item in s)
{
Console.Write(item + ", ");
}
Console.WriteLine();
}
This is going to be integrated into a larger project that requires that I use ObservableCollection
s. At the most, there will probably be 20-50 values being sorted, but this is going to be run on phones and other devices without a lot of computing power, so I would also like to know if this should be optimized or if a different sorting method should be used to improve performance. A stable sort isn't absolutely required, but I would much prefer it. Thanks for any tips ahead of time!
Assert
that you're getting the expected answer using a unit testing framework than to visually check it by writing results results to the console. msdn.microsoft.com/en-us/library/ms182532.aspx \$\endgroup\$ – RubberDuck Dec 18 '14 at 5:29