Popular Posts

Wednesday, February 22, 2012

Counting Sort

Code:

#include <stdio.h>
#include <stdlib.h>

int findbig (int *, int size);
int
main ()
{
  int length, big;
  int *a, *c, *b;
  int j, i;

  printf ("Enter the length of the Array to be sorted:");
  scanf ("%d", &length);
  a = (int *) malloc (sizeof (int) * (length + 1));
  b = (int *) malloc (sizeof (int) * (length + 1));
  printf ("\n Enter the elements one by one");
  for (i = 1; i <= length; i++)
    scanf ("%d", &a[i]);
  big = findbig (a, length);
  c = (int *) malloc (sizeof (int) * (big + 1));
  for (j = 0; j <= big; j++)
    c[j] = 0;

  for (j = 0; j <= length; j++)
    b[j] = 88;

  for (j = 1; j <= length; j++)
    c[a[j]] = c[a[j]] + 1;


  printf ("\n C Array after  c[a[j]] = c[a[j]] + 1\n");
  for (j = 0; j <= big; j++)
    printf ("%d \t", c[j]);
  printf ("\n");

  for (j = 1; j <= big; j++)
    c[j] = c[j] + c[j - 1];

  printf ("\n C Array after   c[j] = c[j] + c[j-1]\n");
  for (j = 0; j <= big; j++)
    printf ("%d \t", c[j]);
  printf ("\n");

  for (j = length; j >= 1; j--)
    {
      b[c[a[j]]] = a[j];
      c[a[j]] = c[a[j]] - 1;
      printf ("\nAfter j = %d\n ", j);
      printf ("B array:");
      for (i = 1; i <= length; i++)
    printf ("%d \t", b[i]);
      printf ("\n C Array:");
      for (i = 0; i <= big; i++)
    printf ("%d \t", c[i]);
      printf ("\n");

    }

  free (a);
  free (b);
  free (c);


}


int findbig (int *array, int size)
{
  int big, i;
  big = array[1];
  for (i = 2; i <= size; i++)
    {
      if (array[i] > big)
    big = array[i];
    }
  return big;
}

1 comment:

  1. Look at the way my acquaintance Wesley Virgin's story launches in this SHOCKING AND CONTROVERSIAL video.

    As a matter of fact, Wesley was in the military-and shortly after leaving-he found hidden, "MIND CONTROL" secrets that the government and others used to get everything they want.

    As it turns out, these are the EXACT same secrets tons of celebrities (especially those who "come out of nothing") and elite business people used to become rich and famous.

    You probably know that you utilize only 10% of your brain.

    That's mostly because the majority of your brain's power is UNTAPPED.

    Maybe that thought has even occurred INSIDE your own brain... as it did in my good friend Wesley Virgin's brain seven years ago, while driving an unlicensed, beat-up bucket of a car with a suspended driver's license and with $3.20 in his bank account.

    "I'm very frustrated with living paycheck to paycheck! When will I become successful?"

    You've taken part in those conversations, am I right?

    Your success story is waiting to start. All you have to do is in YOURSELF.

    UNLOCK YOUR SECRET BRAINPOWER

    ReplyDelete