Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

//created by Mohammad Shaqfeh

#include<stdio.h>
#include<stdlib.h>

void print_array(int* a, int n)


{
int i;
for (i=0;i<n;i++) printf("%d ",a[i]);
printf("\n");
}

int main()
{
int n, *a, i; //declarations related to the array of numbers
int seed, L=1000; double U; //declarations related to random
number generator
int temp, last_unsorted, first_unsorted; //declarations
related to bubble sort algorithm

printf("Please enter the array size (n): ");


scanf("%d", &n);
printf("Please enter the random number generator seed: ");
scanf("%d", &seed);

a=(int*) calloc (n, sizeof(int)); //initializing the array

srand48(seed);
for (i=0; i<n; i++) { U=drand48(); a[i]=U*(L+1);} //filling
the array with random numbers

printf("The array before sorting: \n");


print_array(a,n);
printf("\n");

last_unsorted=n-1; first_unsorted=0;

while (last_unsorted>first_unsorted)
{
for (i=first_unsorted; i<last_unsorted; i++) //forward
iteration
if (a[i]>a[i+1]) {temp = a[i]; a[i]=a[i+1]; a[i+1]=temp;
print_array(a,n);}
last_unsorted--;
for (i=last_unsorted; i>first_unsorted; i--) //backward
iteration
if (a[i]<a[i-1]) {temp = a[i]; a[i]=a[i-1]; a[i-1]=temp;
print_array(a,n);}
first_unsorted++;
}

printf("\nThe array after sorting: \n");


print_array(a,n);

1
}

You might also like