Create a random array of n integers. Sort the array using bubble sort.

Create a random array

Data Structure / Assignment 3 / Set A

#include <stdio.h>
#include <stdlib.h>
void binary_search(int [], int, int, int);
void bubble_sort(int [], int);
int main()
{
int num, size, i;
int list[25];
printf("Enter size of a list: ");
scanf("%d", &size);
printf("\nGenerating random numbers\n");
for(i = 0; i < size; i++)
{
list[i] = rand() % 100;
printf("%d  ", list[i]);
}
bubble_sort(list, size);
printf("\n");
printf("Enter number to search: ");
scanf("%d", &num);
binary_search(list, 0, size, num);
}
void bubble_sort(int list[], int size)
{
int temp, i, j;
for (i = 0; i < size; i++)
{
for (j = i; j < size; j++)
{
if (list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
void binary_search(int list[], int lo, int hi, int num)
{
int mid;
if (lo > hi)
{
printf("\nNumber not found\n");
return;
}
mid = (lo + hi) / 2;
if (list[mid] == num)
{
printf("Number found\n");
}
else if (list[mid] > num)
{
binary_search(list, lo, mid - 1, num);
}
else if (list[mid] < num)
{
binary_search(list, mid + 1, hi, num);
}
}
Output:
Enter size of a list: 6
Generating random numbers
83  86  77  15  93  35  
Enter number to search: 50
Number not found

By Admin

2 thoughts on “b) Create a random array of n integers. Sort the array using bubble sort. Accept a value x from the user and use a binary search algorithm to check whether the number is present in the array or not and output the position if a number is present.”

Leave a Reply

Your email address will not be published. Required fields are marked *