Answer to Question #211589 in C++ for Hemambar

Question #211589

write a c++ program to sort a given set of values your program should overload the function sort so that the same function can be used for sorting values of numeric data type the sort function calls another function called swap which swaps any two values this function can be implemented as a generic function so that it can swap values of any data type. the no of values to be sorted is known only at runtime add appropriate member functions call the function sort using function pointers the values to be sorted are passed as an array to the function


1
Expert's answer
2021-06-29T06:15:17-0400
#include <bits/stdc++.h>
using namespace std;


// A function to implement sorting
void Sort(int arr[], int n)
{
   int i, j;
   for (i = 0; i < n-1; i++)  
for (j = 0; j < n-i-1; j++)
       if (arr[j] > arr[j+1])
           swap(arr[j], arr[j+1]);
}

void Sort(float arr[], int n)
{
   int i, j;
   for (i = 0; i < n-1; i++)  
for (j = 0; j < n-i-1; j++)
       if (arr[j] > arr[j+1])
           swap(arr[j], arr[j+1]);
}

void Sort(double arr[], int n)
{
   int i, j;
   for (i = 0; i < n-1; i++)  
for (j = 0; j < n-i-1; j++)
       if (arr[j] > arr[j+1])
           swap(arr[j], arr[j+1]);
}

void Sort(long arr[], int n)
{
   int i, j;
   for (i = 0; i < n-1; i++)  
for (j = 0; j < n-i-1; j++)
       if (arr[j] > arr[j+1])
           swap(arr[j], arr[j+1]);
}

void Sort(short arr[], int n)
{
   int i, j;
   for (i = 0; i < n-1; i++)  
for (j = 0; j < n-i-1; j++)
       if (arr[j] > arr[j+1])
           swap(arr[j], arr[j+1]);
}

/* Function to print an array */
void printArray(int arr[], int size)
{
   int i;
   for (i = 0; i < size; i++)
       cout << arr[i] << " ";
   cout << endl;
}

// Driver code
int main()
{
  
   int n ;

cout<<"enter number of value:";

cin>>n;

    int arr[n]; 
        cout << "Enter " << n << " items" << endl;
        for (int x = 0; x < n; x++) {
                cin >> arr[x];
        }


   Sort(arr, n);
   cout<<"Sorted array: \n";
   printArray(arr, n);
   return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS