Solution for Exercise 12-15
ex1215
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
const int size = 40;
int bubble[size];
int inner,outer,temp,x;
srand((unsigned)time(NULL));
/* Display original array */
puts("Original Array:");
for(x=0;x<size;x++)
{
/* keep the value between 1 and 100 */
bubble[x] = rand() % 100 + 1;
printf("%d\t",bubble[x]);
}
putchar('\n');
/* Bubble sort */
for(outer=0;outer<size-1;outer++)
{
for(inner=outer+1;inner<size;inner++)
{
if(bubble[outer] < bubble[inner])
{
temp=bubble[outer];
bubble[outer] = bubble[inner];
bubble[inner] = temp;
}
}
}
/* Display sorted array */
puts("Sorted Array:");
for(x=0;x<size;x++)
printf("%d\t",bubble[x]);
putchar('\n');
return(0);
}
Output
Original Array:
33 30 22 51 26 50 84 35 22 86 44 63 27 13 53 32 7 74 86 44 49 10 6 49 62 18 14 8 62 19 99 37 28 87 93 45 44 8 57 54
Sorted Array:
99 93 87 86 86 84 74 63 62 62 57 54 53 51 50 49 49 45 44 44 44 37 35 33 32 30 28 27 26 22 22 19 18 14 13 10 8 8 7 6
Notes
* To reverse sort, switch the > operator to < at Line 27.
Copyright © 1997-2025 by QPBC.
All rights reserved
