0% found this document useful (0 votes)
8 views2 pages

Bubble Sort in C with For Loop

This C code implements bubble sort to sort an array of random numbers. It takes user input for the array size and random seed. The array is initialized with random numbers between 0 and 1000 using the seed. Bubble sort is then applied using two nested loops - an outer loop tracks the unsorted range, and inner loops perform forward and backward iterations to swap adjacent elements out of order until the array is fully sorted. The array is printed before and after sorting.

Uploaded by

iman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Bubble Sort in C with For Loop

This C code implements bubble sort to sort an array of random numbers. It takes user input for the array size and random seed. The array is initialized with random numbers between 0 and 1000 using the seed. Bubble sort is then applied using two nested loops - an outer loop tracks the unsorted range, and inner loops perform forward and backward iterations to swap adjacent elements out of order until the array is fully sorted. The array is printed before and after sorting.

Uploaded by

iman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

//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