0

I'm trying to implement a bucket sort using a resizable vector function that I made. The vector works fine, but I get a segmentation fault anytime I try to run my sort function. Can anyone help me remedy this? Notes about code: K=# of buckets in this case 10. find_max and find_min do exactly what you'd expect. vector_int_construct initializes an array and vector_int_push_back pushes integers to the end of the array. vector_int_sort just calls on a merge_sort function I created that also works fine on its own.

typedef struct {
  size_t size;
  size_t maxsize;
  int* array;
}
vector_int_t;

void bucket_sort( int* a, size_t size )
{
  int min = find_min( a, size );
  int max = find_max( a, size );
  size_t range = (( max - min ) / K );
  vector_int_t buckets[K]; 
  for( size_t i = 0; i < K; i++ ) {
    vector_int_construct( &buckets[i] );
    for( size_t j = 0; j < range; j++ ) {
      vector_int_push_back( &buckets[i], a[j] );
    }  
  }
  for( size_t i = 0; i < K; i++ ) {
    vector_int_sort( &buckets[i] );
  }
  size_t cnt = 0;
  while( cnt != size ) {
    for( size_t i = 0; i < K; i++ ) {
      for( size_t j = 0; j < vector_int_size( &buckets[i] ); j++ ) {
        a[cnt] = buckets[i].array[j];
        cnt++;
      }
    }
  }
}

int main()
{
  size_t size = 4;
  int    a[]  = { 19, 95, 4, 23 };

  // Print out array before

  printf( "Before sorting: " );

  ece2400_print_array( a, size );

  // Call sort

  bucket_sort( a, size );

  // Print out array after

  printf( "After sorting:  " );

  ece2400_print_array( a, size );

  return 0;
}
bamfot13
  • 1
  • 1

0 Answers0