Tuesday, November 29, 2011

Counting Sort dalam bahasa C


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

#define UINT unsigned int
#define MAX 100
#define INPUT 'i'
#define OUTPUT 'o'
#define _MY_DEBUG
#if defined(_MY_DEBUG)
 #define TRACE_LINE printf("\n\n- Program Statistics :\n1. File : %s\n2. Date : %s\n3. Time : %s\n",__FILE__,__DATE__,__TIME__);
#else
 #define TRACE_LINE
#endif

void InputOutput(long*, const long, const char);
int CountingSort(long*, const long, const long);
void FreeBuffer(long*);

int main(int argc, char *argv[]) {
 system("COLOR 5");
 long *buffer = NULL, max;
 printf("Implementasi Counting Sort\nMasukkan jumlah data [MAX:100] : ");
 scanf("%ld",&max);
 fflush(stdin);
 if((max > 0) && (max <= MAX)) {
  buffer = (long*)calloc(max,sizeof(long));
  InputOutput(buffer,max,INPUT);
  printf("\nData yang anda masukkan : ");
  InputOutput(buffer,max,OUTPUT);
  if(!CountingSort(buffer,max,65535)) { // 2147483647
   /* Jika user menginputkan nilai lebih besar atau sama dengan 65535
   kedalam array buffer, maka Fungsi CountingSort tidak akan bekerja
   sesuai dengan fungsinya atau bisa mengakibatkan program Error / akan
   terjadi Segmentation Fault */
   printf("\nData setelah disorting : ");
   InputOutput(buffer,max,OUTPUT);
  } FreeBuffer(buffer);
 }
 TRACE_LINE;
 getch();
 fflush(stdin);
 return(EXIT_SUCCESS);
}

void InputOutput(long* buffer, const long max, const char STAT) {
 long i;
 if('i' == STAT) {
  for(i = 0; i < max; ++i) {
   printf("%ld. Data ke-%ld : ",(i+1),(i+1));
   scanf("%ld",&buffer[i]);
   fflush(stdin);
  }
 } else if('o' == STAT) {
  for(i = 0; i < max; ++i) {
   printf("%ld ",buffer[i]);
  }
 }
}

int CountingSort(long* buffer, const long max, const long value) {
 long i, j, OutputPos;
    long* counts = (long*)calloc(value,sizeof(long));
    if(counts == NULL) {
     printf("\nError : No Memory Available for Counts!");
     return(1);
    } else {
     for(i = 0; i < max; ++i) {
   ++counts[buffer[i]];
  } OutputPos = 0;
  for(i = 0; i < value; ++i) {
   for(j = 0; j < counts[i]; ++j) {
    buffer[OutputPos] = i;
    ++OutputPos;
   }
  } FreeBuffer(counts);
    }
    return(0);
}

void FreeBuffer(long* buffer) {
 free(buffer);
 buffer = NULL;
}

2 comments:

  1. materinya bagus gan, semoga materi counting sortnya bsa saling melengkapi
    .
    www.markijar.blogspot.com/2015/04/contoh-program-counting-sort-c.html

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete