Write a C++ program to read a list of values from the user and then sort them in
ID: 3856422 • Letter: W
Question
Write a C++ program to read a list of values from the user and then sort them
in ascending order using Bubble sort. Your program should perform the following tasks.
First your program should ask the user for the number of values in the list.
Next, you should call a function to read the values from the user – you should define a
function for reading the input values - the function should the array to store user input
values as input parameter. The second parameter should be number of values to input. (You
can use the function readArray ).
Write a function named bubbleSort which should take the list and its length as input
parameters. The function should sort the values of the list and print the updated list
Explanation / Answer
Hi,
Below is the answer-
#include <iostream>
using namespace std;
//Bubble Sort
void bubble_sort (int arr[], int n)
{
for (int i = 0; i < n; ++i)
for (int j = 0; j < n - i - 1; ++j)
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
void array_input(int arr1[],int n){
for(int i=0;i<n;i++){
cout<<"Enter element"<<i;
cin>>arr1[i];
}
}
//Driver Function
int main()
{ int n;
int input_ar[20];
//int input_ar[] = {10, 50, 21, 2, 6, 66, 802, 75, 24, 170};
//int n = sizeof (input_ar) / sizeof (input_ar[0]);
cout<<"Please enter the number of elements";
cin>>n;
array_input(input_ar,n);
bubble_sort (input_ar, n);
cout << "Sorted Array : " << endl;
for (int i = 0; i < n; ++i)
cout << input_ar[i] << " ";
return 0;
}
Regards,
Vinay Singh
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.