In: Computer Science
Write a Y86 program in C language that sorts an array of data using Bubble Sort. Allow the user to input up to 10 numbers from the keyboard. Sort the array in place (i.e., no need to allocate additional memory for the sorted array). Your program should be a complete one
Solution:
Code (PLEASE REFER THE SCREENSHOT FOR CODE INDENTATION):
#include <stdio.h>
int main()
{
int array[10] = {0};
int numOfData;
int i = 0, j = 0;
int temp = 0;
/* prompt the user to enter number of elements in the array
*/
printf("Enter the number of elements in array (up to 10): ");
scanf("%d", &numOfData);
if(numOfData > 10)
{
printf("Entered value is greater than 10. Please try again with
value up to 10.");
return 0;
}
/* prompt the user to enter data */
for(i = 0; i < numOfData; i++)
{
printf("Enter data #%d: ", i);
scanf("%d", &array[i]);
}
/* Bubble sort the array
After the first iteration the last element will be at sorted
position
After second iteration the second last element will be at sorted
position
and so on.
*/
/* loop for numOfData - 1 (one less than the total number of
elements) in the array */
for(i = 0; i < numOfData -1; i++)
{
/* After every iteration one element is at sorted position,
so loop till the number of unsorted items */
for(j = 0; j < numOfData - i - 1; j++)
{
/* swap the element in the array */
if(array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
/* diaplay the sorted array */
printf("Sorted array: ");
for(i = 0; i < numOfData; i++)
{
printf("%d ", array[i]);
}
return 0;
}
Output: