# Counting sort using arrays

This is my implantation of counting sort, but I see myself using way too many for loops. Is this necessary?

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
public static int[] a = { 0,0,0,5,4,8,9,9,7,3, 3, 2, 1 };
public static void Sorting()
{
int j = 0, i = 0, smallestvalue = 0, largestvalue = 0, n = a.Length, lengthof_B = 0, temp = 0, anothersmallestvalue;
smallestvalue = largestvalue = a[0];
for (i = 0; i < n; i++)
{
if (smallestvalue > a[i])
{
smallestvalue = a[i];
}
else if (largestvalue < a[i])
{
largestvalue = a[i];
}
}
int x = anothersmallestvalue = smallestvalue;

lengthof_B = largestvalue - smallestvalue + 1;
int[] b = new int[lengthof_B];
for (i = 0; i < lengthof_B && smallestvalue <= largestvalue; i++)
{
for (j = 0; j < n; j++)
{
if (smallestvalue == a[j])
{
b[i] = b[i] + 1;
}
}
b[i] = temp + b[i];
temp = b[i];
smallestvalue++;
}
int[] c = new int[a.Length];
for (i = n - 1; i >= 0; i--)
{
anothersmallestvalue = x;
for (j = 0; j <= lengthof_B ; j++)        //{3,3,2,1}
{
if (a[i] == anothersmallestvalue)
{
temp = b[j];
c[temp-1] = anothersmallestvalue;
b[j] = b[j] - 1;
}
anothersmallestvalue++;
}
}
for (i = 0; i < c.Length; i++)
{
Console.WriteLine("c[i] : " + c[i]);
}
}
}
class Demo
{
static void Main(string[] args)
{
Program.Sorting();
}
}
}


I'm sorry, but I think this is the time where it's easier to start from scratch then try to fix your code.

Let me comment on some of your styling choices:

• Don't use words like smallest/anothersmallest/largest etc - use min/max.
• Respect the CamelCase for long variable names.
• Don't initialize your loop counter in the beginning where you initialize all other variables.
• n is unnecessary and while you created it - you don't use it everywhere.

# Logic

The first loop where you calculate min and max is fine.

The second loop inside the loop is not necessary. Instead you could just use something like (assuming you would use min for smallest value and counts for temp array):

for (int i=0; i<a.length; i++) {
counts[a[i]-min]++
}


The third loop where you populate result back on what you counted so far can be written like:

int j=0;
for (int i=0; i<counts.length; i++) {
while (counts[i] > 0) {
result[j] = i + min;
counts[i]--;
j++;
}
}

• Thanks Very usefull answer Once more Thanks I will Implement It again Nov 28, 2015 at 17:29