I did not spend a significant amount of time removing potential issues with this code, but then, neither do most examples of the Counting Sort; there are more interesting algorithms ahead. The most obvious flaws in this particular implementation are as follows:
namespace Algorithms
{
class CountingSort
{
public int[] Sort()
{
//creates array
int[] arrayToSort = { 2, 1, 2, 1, 3, 0, 3, 4, 4, 3, 0, 2, 1, 3, 5, 1, 3 };
//create array for bucket
int min = 0;
int max = 0;
for (int counter = 0; counter < arrayToSort.Length; counter++)
{
if (arrayToSort[counter] < min)
{
min = arrayToSort[counter];
}
if (arrayToSort[counter] > max)
{
max = arrayToSort[counter];
}
}
int[] arrayBucket = new int[max - min + 1];
//count items into buckets
for (int counter = 0; counter < arrayToSort.Length; counter++)
{
arrayBucket[arrayToSort[counter]]++;
}
//sort buckets back into array
//count items into buckets
int lastPosition = 0;
for (int counter = 0; counter < arrayBucket.Length; counter++)
{
for (int innerCounter = 0; innerCounter < arrayBucket[counter]; innerCounter++)
{
arrayToSort[lastPosition++] = counter;
}
}
return arrayToSort;
}
}
}
- It cannot handle negative integers
- It is designed only for integers.
namespace Algorithms
{
class CountingSort
{
public int[] Sort()
{
//creates array
int[] arrayToSort = { 2, 1, 2, 1, 3, 0, 3, 4, 4, 3, 0, 2, 1, 3, 5, 1, 3 };
//create array for bucket
int min = 0;
int max = 0;
for (int counter = 0; counter < arrayToSort.Length; counter++)
{
if (arrayToSort[counter] < min)
{
min = arrayToSort[counter];
}
if (arrayToSort[counter] > max)
{
max = arrayToSort[counter];
}
}
int[] arrayBucket = new int[max - min + 1];
//count items into buckets
for (int counter = 0; counter < arrayToSort.Length; counter++)
{
arrayBucket[arrayToSort[counter]]++;
}
//sort buckets back into array
//count items into buckets
int lastPosition = 0;
for (int counter = 0; counter < arrayBucket.Length; counter++)
{
for (int innerCounter = 0; innerCounter < arrayBucket[counter]; innerCounter++)
{
arrayToSort[lastPosition++] = counter;
}
}
return arrayToSort;
}
}
}
Comments
Post a Comment