I am making a program that sorts integers in ascending and descending order through bubble sort algorithm in C. So, I am providing a random data of 20 integers(fixed)first and then deciding in which manner to sort it, which is basically done through simple menu system which is like:
A. provide random data
B. Sort high to low
C. Sort low to high
*I want to print a message "Data not provided" if the user tries to sort without getting the random data first.
Code below:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void random_number_list(int array[]);
void low_to_high(int array[]);
void high_to_low(int array[]);
void display(int array[]);
int main(void)
{
int original_array[21];
char selection;
do
{
puts("----> Please make your selection from the following:\n\n"
" A.Define Random Number List\n"
" B.Sort Number List(High to Low)\n"
" C.Sort Number List(Low to High)\n"
" D.Exit ");
printf_s(" \nYour selection: ");
scanf_s("\n%c", &selection);
if (selection == 'A' || selection == 'a')
{
random_number_list(original_array);
}
else if (selection == 'B' || selection == 'b')
{
high_to_low(original_array);
}
else if (selection == 'C' || selection == 'c')
{
low_to_high(original_array);
}
else if (selection == 'D' || selection == 'd')
{
puts("\nThank you for using the application.\n");
return 0;
}
else
{
puts("\nSorry, input not understood. Please try again.\n");
}
}
while (selection != 'D');
}
void random_number_list(int array[])
{
srand(time(NULL));
printf("\n\nThe Random Data: ");
for (size_t i = 0; i < 20; i++)
{
array[i] = 1 + rand() % 100;
printf_s("%d,", array[i]);
}
puts("\n\n");
}
void low_to_high(int array[])
{
int i, j, temp;
for (i = 0;i < 20 - 1;i++)
{
for (j = i + 1;j < 20;j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
display(array);
printf("\n");
}
}
}
printf_s("\nSorted Data : ");
display(array);
puts("\n");
}
void high_to_low(int array[])
{
int i, j, temp;
for (i = 0; i < 20 - 1; i++)
{
for (j = i + 1; j < 20; j++)
{
if (array[i] < array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
display(array);
printf("\n");
}
}
}
printf_s("\nSorted Data : ");
display(array);
puts("\n");
}
void display(int array[])
{
for (size_t i = 0; i < 20; i++)
{
printf("%d,", array[i]);
}
}