PLEASE SOLVE THIS C++ PROGRAM IN AN EASY LANGUAGE WAY DIFFERENT THEN THE TEXTBOOK ANSWER
The bubble sort is another technique for sorting an array. A bubble sort compares adjacent array elements and exchanges their values if they’re out of order. In this way, the smaller values “bubble” to the top of the array (toward element 0), while the larger values sink to the bottom of the array. After the first pass of a bubble sort, the last array element is in the correct position; after the second pass, the last two elements are correct, and so on. Thus, after each pass, the unsorted portion of the array contains one less element. Write and test a function that implements this sorting method.
Code:
#include <iostream>
using namespace std;
//function to print Elements in the array
void print_array(int a[],int n)
{
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
}
//function to sort Elements in descending order
void bubble_Sortd(int a[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
if (a[j] < a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
//function to sort Elements in ascending order
void bubble_Sorta(int a[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
if (a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
//driver function
int main()
{
int arr[10],n;
cout<<"Enter Number of elements? ";
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Array: ";
print_array(arr,n);
bubble_Sortd(arr,n);
cout<<"\nSorted array in descending order: ";
print_array(arr,n);
cout<<"\nSorted array in ascending order: ";
bubble_Sorta(arr,n);
print_array(arr,n);
return 0;
}
Screenshot:
Output:
here I have sorted array in ascending and descending array both.
Get Answers For Free
Most questions answered within 1 hours.