aboutsummaryrefslogblamecommitdiff
path: root/bsort.c
blob: 56f896998ec6044aab9c990d3a3a97c5774398c8 (plain) (tree)










































































                                                
#include <stdio.h>

void print_array(int array[], int len);
void buble_sort(int array[], int len);
void buble_sort_rec(int array[], int len);
void swap(int *to, int *from);

int 
main(void)
{
  int array[] = {4, 2, 1, 7, 8, 9, 6, 0, 3, 5};

  print_array(array, sizeof(array)/sizeof(int));
  buble_sort(array, sizeof(array)/sizeof(int));
  print_array(array, sizeof(array)/sizeof(int));

  return 0;
}

void
print_array(int array[], int len)
{
  while (len--)
    printf("%d, ", *array++);

  printf("\n");
}

void
buble_sort(int array[], int len)
{
  int active, len_cp = len;

  while (--len_cp) {
    if (len_cp == len - 1) {
      active = 0;
    }

    if (array[len_cp] < array[len_cp - 1]) {
      swap(&array[len_cp], &array[len_cp - 1]);
      active = 1;
    }

    if (len_cp == 1 && active)
      len_cp = len;
  }
}



void
buble_sort_rec(int array[], int len)
{
  int active = 0, len_cp = len;

  while (--len_cp > 0)
    if (array[len_cp] < array[len_cp - 1]) {
      swap(&array[len_cp], &array[len_cp - 1]);
      active = 1;
    }

  if (active)
    buble_sort(array, len);
  else
    return;
}

void
swap(int *to, int *from)
{
  int buff = *to;

  *to = *from;
  *from = buff;
}