Can counting sort sort in descending order?

This is a discussion on Can counting sort sort in descending order? within the C Programming forums, part of the General Programming Boards category; Hi, Can anyone tell me if "counting sort" can be made to sort in desending order? thnx...

  1. #1
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020

    Can counting sort sort in descending order?

    Hi,

    Can anyone tell me if "counting sort" can be made to sort in desending order?

    thnx

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Of course:
    Code:
    static void counting_sort ( int *array, int size )
    {
      int *counter;
      int i, j, k = size - 1;
      int max = array[0];
    
      for ( i = 0; i < size; i++ ) {
        if ( array[i] > max )
          max = array[i];
      }
    
      counter = malloc ( ( max + 1 ) * sizeof *counter );
      if ( counter == NULL )
        return;
    
      for ( i = 0; i < max; i++ )
        counter[i] = 0;
    
      for ( i = 0; i < size; i++ )
        counter[array[i]]++;
    
      for ( i = 0; i < max + 1; i++ ) {
        for ( j = 0; j < counter[i]; j++ )
          array[k--] = i;
      }
    
      free ( counter );
    }
    -Prelude
    Last edited by Prelude; 03-06-2003 at 09:59 AM.
    My best code is written with the delete key.

  3. #3
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020
    But how is your version descending? It looks different from the one on http://www.cs.cf.ac.uk/user/C.L.Mumf...ountPage.html.

    thnx

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >But how is your version descending?
    Instead of copying from 0 to size-1 into array, you do the reverse for a descending sort.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 02:27 PM
  2. selection sort records of chars
    By hew in forum C++ Programming
    Replies: 8
    Last Post: 04-23-2002, 04:49 PM
  3. Help me sort the names in alpha order.
    By cazil in forum C++ Programming
    Replies: 2
    Last Post: 02-04-2002, 02:30 PM
  4. Replies: 1
    Last Post: 01-06-2002, 06:28 PM
  5. selection sorting using going-down and going-up recursion
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 11-02-2001, 02:29 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21