This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, February 17, 2023

Write a program to sort N numbers in ascending order using a function template.

 Here's a program to sort N numbers in ascending order using a function template:

#include <iostream>
using namespace std;

template <class T>
void sort_array(T arr[], int n) {
    for (int i = 0; i < n; i++) {
        for (int j = i+1; j < n; j++) {
            if (arr[i] > arr[j]) {
                T temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

int main() {
    int n;
    cout << "Enter the number of elements: ";
    cin >> n;
    int int_arr[n];
    cout << "Enter the integers: ";
    for (int i = 0; i < n; i++){
        cin >> int_arr[i];
    }
    sort_array(int_arr, n);
    cout << "Sorted array: ";
    for (int i = 0; i < n; i++){
        cout << int_arr[i] << " ";
    }
    return 0;
}

In this program, we first declare a function 'sort_array' that takes an array of any datatype 'T' and its size 'n'. This function sorts the array using a simple bubble sort algorithm.

Then in the 'main' function, we ask the user for the number of elements and the integers to be stored. And we declare an array of the integers and fill it with the user's input. We then call the 'sort_array' function with the array and its size,  and print the sorted array.


No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget