Skip to content

Instantly share code, notes, and snippets.

@sergiobuj
Created September 7, 2011 00:44
Show Gist options
  • Save sergiobuj/1199436 to your computer and use it in GitHub Desktop.
Save sergiobuj/1199436 to your computer and use it in GitHub Desktop.
Counting sort written in C
/* @(#)counting_sort_cool.c
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
/* #include "counting_sort.h"
*/
int main(int argc, char * argv[])
{
int i, A_size;
scanf("%d", &A_size);
int *A = malloc(sizeof(int)*A_size);
for(i = 0; i < A_size; ++i)
scanf("%d", &A[i]);
int *B = malloc(sizeof(int)* A_size);
int k = 0;
clock_t t1 = clock();
for(i = 0; i < A_size; ++i ){
if( A[i] > k){
k = A[i];
}
}
int *C = malloc(sizeof(int)* k+1); /* +1 because of the zero */
for(i = 0; i <= k; ++i){ C[i] = 0; }
/* Count appearances */
for(i = 0; i < A_size; ++i){
C[A[i]]++;
}
/* Accumulate number of appearances */
for(i = 1; i <= k; ++i){
C[i] = C[i-1] + C[i];
}
/* Assign the number from A to a pos -1 in B (because of the zero in C)*/
for(i = A_size-1; i >= 0 ; --i){
B[ C[ A[i] ] -1 ] = A[i];
C[A[i]]--;
}
printf("Finished in %lf clocks per second\n", (double)(clock() - t1) / CLOCKS_PER_SEC);
/* Print both arrays */
puts("A");
for(i = 0; i < A_size -1; i++){
printf("%d, ", A[i]);
} printf("%d\n", A[A_size -1]);
puts("B");
for(i = 0; i < A_size -1; i++){
printf("%d, ", B[i]);
} printf("%d\n", B[A_size -1]);
free(A);
free(B);
free(C);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment