sorting-visualization/SortingVisualization/Algorithms/Gravitysort.cs

44 lines
1.4 KiB
C#

using System;
namespace SortingVisualization.Algorithms {
public class Gravitysort : SortingAlgorithm {
public override string GetAlgorithmName() => "Gravitysort";
public override void Sort(ref DataSet set) {
Simulate(ref set);
System.Console.WriteLine("Doing {0}...", this.GetAlgorithmName());
int i, j, max, sum;
byte[] beads;
for (i = 1, max = set.ReadOperation(0); i < set.Size; ++i)
if (set.ReadOperation(i) > max)
max = set.ReadOperation(i);
beads = new byte[max * set.Size];
for (i = 0; i < set.Size; ++i)
for (j = 0; j < set.ReadOperation(i); ++j)
beads[i * max + j] = 1;
for (j = 0; j < max; ++j) {
for (sum = i = 0; i < set.Size; ++i) {
sum += beads[i * max + j];
beads[i * max + j] = 0;
}
for (i = set.Size - sum; i < set.Size; ++i)
beads[i * max + j] = 1;
}
for (i = 0; i < set.Size; ++i) {
for (j = 0; j < max && Convert.ToBoolean(beads[i * max + j]); ++j)
;
set.WriteOperation(i, j);
}
System.Console.WriteLine("{0} complete!", this.GetAlgorithmName());
if (!set.SimulateMode)
set.FinalizeVideo();
}
}
}