Bubble Sort
2003-03-27 23:45:38
Category: c:math
Description: Use bubble sort method to sort an array of integers.
Author: detour
Viewed: 55994
Rating: (212 votes)


/* bubble.c by detour@metalshell.com
 *
 * Use the very simple and slow bubble sort method to 
 * sort an array of integers.
 * 
 * http://www.metalshell.com/
 *
 */
 
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
 
#define ARRAY_SIZE 20
 
void print_array(int *array) {
  int x;
  for(x = 0; x < ARRAY_SIZE; x++) {
    if(x != ARRAY_SIZE-1)
      fprintf(stdout, "%d, ", array[x]);
    else
      fprintf(stdout, "%d\n", array[x]);
  }
}
 
int main() {
  int iarray[ARRAY_SIZE];
  int x, y, holder;
 
  // Seed rand()
  srand((unsigned int)time(NULL));
 
  for(x = 0; x < ARRAY_SIZE; x++)
    iarray[x] = (int)(rand() % 100);
 
  fprintf(stdout, "Before Sort\n---------------\n");
  print_array(iarray);  
 
 
  // Bubble sort method.
  for(x = 0; x < ARRAY_SIZE; x++)
    for(y = 0; y < ARRAY_SIZE-1; y++)
      if(iarray[y] > iarray[y+1]) {
        holder = iarray[y+1];
        iarray[y+1] = iarray[y];
        iarray[y] = holder;
      }
 
  fprintf(stdout, "\nAfter Sort\n---------------\n");
  print_array(iarray);  
 
}