BUBBLE SORT
Implemented using C Language
C Language Code:
BUBBLE.C
#include <stdlib.h>
#include <stdio.h>
#include <process.h>
#define NUM_ITEMS 5
void bubbleSort(int numbers[], int array_size);
void prnArray(int numbers[], int array_size) ;
int numbers[NUM_ITEMS];
void main()
{
int i;
clrscr() ;
//seed random number generator
srand(getpid());
//fill array with random integers
for (i = 0; i < NUM_ITEMS; i++)
numbers[i] = rand();
printf("\nBefore Bubble Sort.\n");
prnArray(numbers, NUM_ITEMS) ;
//perform bubble sort on array
bubbleSort(numbers, NUM_ITEMS);
printf("\nAfter Bubble sort.\n");
prnArray(numbers, NUM_ITEMS) ;
}
void prnArray(int numbers[], int array_size)
{
int x ;
for(x=0; x < array_size; x++)
printf("%d\t", numbers[x]) ;
}
void bubbleSort(int numbers[], int array_size)
{
int i, j, temp, cnt=1;
for (i = (array_size - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (numbers[j-1] > numbers[j])
{
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
printf("\n After Pass %d\t" , cnt++) ;
prnArray(numbers, NUM_ITEMS) ;
}
}
No comments:
Post a Comment