C Program to Sort Random Array Using Bubble Sort and rand() function

Problem:

Write a c program for bubble sort on random numbers. Write a C program to sort an array of n (accept value of n from user) random numbers using bubble sort algorithm in C. Generate the random numbers using rand() function in C.

Algorithm / Solution:

Here is the solution of c program to sort array of random numbers using bubble sort
  1. Start
  2. Define a generate function which accepts pointer to array and integer value to generate a random array.
  3. In generate() function use rand() function to generate a random number. Do rand()%100 to get last two digits of random number and assign this to corresponding array position.
  4. Accept 'how many elements to generate in array?'.
  5. Pass this to generate() function. This will create a random array.
  6. Now apply bubble sort on this random array.
  7. Display random array and sorted array.
  8. End.

C Program / Source Code:

Here is the source code of C program to sort array of random numbers using bubble sort using function in C
/* Aim: Write a C program to sort array of random numbers using bubble sort and rand() function */

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

// generate_random() function to generate array of random numbers

void generate_random(int *a,int n)
{
	int i;

	for(i=0;i<n;i++)
	a[i]=rand()%100;

}

void main()
{
	int a[100],n,i,j,temp;

	printf("\n Enter size of array:- ");
	scanf("%d",&n);
 
// Passing starting address and size to generate array of random numbers
	generate_random(a,n); 

// Displaying the random array

	printf("\n The random array: ");
	for(i=0;i<n;i++)
		printf(" %d ",a[i]);
 

	for(i=1;i<n;i++)
	{
		for(j=0;j<n-i;j++)
		{
/* To sort in ascending order, change '<' to '>' to implement descending order sorting */
			if(a[j+1]<a[j]) 
			{
				temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp; 
			}
		}
	}
 

// Displaying the sorted array.

	printf("\n The sorted array: ");
	for(i=0;i<n;i++)
	printf(" %d ",a[i]);
	printf("\n \n");

}

/* Output of above code / Runtime cases:-

 Enter size of array:- 5

 The random array:  83  86  77  15  93 
 The sorted array:  15  77  83  86  93 

*/