HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

Counting sort using arrays

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortarrayscountingusing

Problem

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  a[i])
                {
                    smallestvalue = a[i];
                }
                else if (largestvalue = 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();
            Console.ReadLine();
        }
    }
}

Solution

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 0) {
      result[j] = i + min;
      counts[i]--;
      j++;
   }
}

Code Snippets

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

Context

StackExchange Code Review Q#112153, answer score: 2

Revisions (0)

No revisions yet.