Program for sorting variables of any data type

Write a program for sorting variables of any datatype without the use of std::sort .
Examples:
Input : 2000, 456, -10, 0
Output : -10 0 456 2000
Input : "We do nothing"
"Hi I have something"
"Hello Join something!"
"(Why to do work)"
Output :(Why to do work)
Hello Join something!
Hi I have something
We do nothing
The examples above show, we can have any data type elements present as an input and output will be in a sorted form of the input data. The idea here to solve this problem is to make a template.
Method 1 (Writing our own sort) In below code, we have implemented Bubble Sort to sort the array.Â
CPP
// CPP program to sort array of any data types.#include <bits/stdc++.h>using namespace std;Â
// Template formed so that sorting of any // type variable is possibletemplate <class T>void sortArray(T a[], int n){     // boolean variable to check that     // whether it is sorted or not    bool b = true;    while (b) {        b = false;        for (size_t i=0; i<n-1; i++) {Â
            // swapping the variable            // for sorting order            if (a[i] > a[i + 1]) {                T temp = a[i];                a[i] = a[i + 1];                a[i + 1] = temp;                b = true;            }        }    }}Â
// Template formed so that sorting of any // type variable is possibletemplate <class T>void printArray(T a[], int n){Â Â Â Â for (size_t i = 0; i < n; ++i) Â Â Â Â Â Â Â Â cout << a[i] << " "; Â Â Â Â cout << endl;}Â
// Driver codeint main(){Â Â Â Â int n = 4;Â Â Â Â int intArr[n] = { 2000, 456, -10, 0 };Â Â Â Â sortArray(intArr, n);Â Â Â Â printArray(intArr, n);Â
    string strArr[n] = { "We do nothing",                        "Hi I have something",                        "Hello Join something!",                        "(Why to do work)" };    sortArray(strArr, n);    printArray(strArr, n);Â
    float floatArr[n] = { 23.4, 11.4, -9.7, 11.17 };    sortArray(floatArr, n);    printArray(floatArr, n);Â
    return 0;} |
Java
import java.util.Arrays;Â
class Main {    // Generic method for sorting an array of any type    public static <T extends Comparable<T>> void sortArray(T[] a) {        boolean sorted;        do {            sorted = true;            for (int i = 0; i < a.length - 1; i++) {                // Compare adjacent elements and swap them if they are out of order                if (a[i].compareTo(a[i + 1]) > 0) {                    T temp = a[i];                    a[i] = a[i + 1];                    a[i + 1] = temp;                    sorted = false;                }            }        } while (!sorted); // Repeat the process until the array is sorted    }Â
    // Generic method for printing an array of any type    public static <T> void printArray(T[] a) {        for (T value : a) {            // Print each element followed by a space            System.out.print(value + " ");        }        System.out.println(); // Move to the next line after printing the array    }Â
    public static void main(String[] args) {        Integer[] intArr = { 2000, 456, -10, 0 };        sortArray(intArr); // Sort the array of integers        printArray(intArr); // Print the sorted integer arrayÂ
        String[] strArr = { "We do nothing",                            "Hi I have something",                            "Hello Join something!",                            "(Why to do work)" };        sortArray(strArr); // Sort the array of strings        printArray(strArr); // Print the sorted string arrayÂ
        Float[] floatArr = { 23.4f, 11.4f, -9.7f, 11.17f };        sortArray(floatArr); // Sort the array of floating-point numbers        printArray(floatArr); // Print the sorted float array    }} |
Python
def sort_array(a):    sorted = False    while not sorted:        sorted = True        for i in range(len(a) - 1):            # Compare adjacent elements and swap them if they are out of order            if a[i] > a[i + 1]:                a[i], a[i + 1] = a[i + 1], a[i]                sorted = FalseÂ
# Generic method for printing an array of any typedef print_array(a):    for value in a:        # Print each element followed by a space        print(value),    print() # Move to the next line after printing the arrayÂ
# Main functionif __name__ == "__main__":    int_arr = [2000, 456, -10, 0]    sort_array(int_arr) # Sort the array of integers    print_array(int_arr) # Print the sorted integer arrayÂ
    str_arr = ["We do nothing",               "Hi I have something",               "Hello Join something!",               "(Why to do work)"]    sort_array(str_arr) # Sort the array of strings    print_array(str_arr) # Print the sorted string arrayÂ
    float_arr = [23.4, 11.4, -9.7, 11.17]    sort_array(float_arr) # Sort the array of floating-point numbers    print_array(float_arr) # Print the sorted float array |
C#
// C# program to sort array of any data types.using System;Â
class GFG{    // Template formed so that sorting of any    // type variable is possible    static void SortArray<T>(T[] a)        where T : IComparable<T>    {        // boolean variable to check that        // whether it is sorted or not        bool b = true;        while (b)        {            b = false;            for (int i = 0; i < a.Length - 1; i++)            {                // swapping the variable                // for sorting order                if (a[i].CompareTo(a[i + 1]) > 0)                {                    T temp = a[i];                    a[i] = a[i + 1];                    a[i + 1] = temp;                    b = true;                }            }        }    }Â
    // Template formed so that sorting of any    // type variable is possible    static void PrintArray<T>(T[] a)    {        foreach (T element in a)        {            Console.Write(element + " ");        }        Console.WriteLine();    }Â
    // Driver code    static void Main()    {        int[] intArr = { 2000, 456, -10, 0 };        SortArray(intArr);        PrintArray(intArr);Â
        string[] strArr = { "We do nothing",                            "Hi I have something",                            "Hello Join something!",                            "(Why to do work)" };        SortArray(strArr);        PrintArray(strArr);Â
        float[] floatArr = { 23.4f, 11.4f, -9.7f, 11.17f };        SortArray(floatArr);        PrintArray(floatArr);    }}Â
Â
// This code is contributed by Vaibhav Nandan |
Output
-10 0 456 2000 (Why to do work) Hello Join something! Hi I have something We do nothing -9.7 11.17 11.4 23.4
Method 2 (Using Library Function) We can use std::sort in C++ to sort array of any data type.Â
CPP
// CPP program to sort array of any data types.#include <bits/stdc++.h>using namespace std;Â
// Template formed so that sorting of any // type variable is possibletemplate <class T>void printArray(T a[], int n){Â Â Â Â for (size_t i = 0; i < n; ++i) Â Â Â Â Â Â Â Â cout << a[i] << " "; Â Â Â Â cout << endl;}Â
// Driver codeint main(){Â Â Â Â int n = 4;Â Â Â Â int intArr[n] = { 2000, 456, -10, 0 };Â Â Â Â sort(intArr, intArr + n);Â Â Â Â printArray(intArr, n);Â
    string strArr[n] = { "We do nothing",                        "Hi I have something",                        "Hello Join something!",                        "(Why to do work)" };    sort(strArr, strArr + n);    printArray(strArr, n);Â
    float floatArr[n] = { 23.4, 11.4, -9.7, 11.17 };    sort(floatArr, floatArr+n);    printArray(floatArr, n);Â
    return 0;} |
Java
// Java program to sort array of any data types.import java.util.Arrays;Â
public class Main {Â Â Â Â public static void printArray(int[] a) {Â Â Â Â Â Â Â Â for (int i = 0; i < a.length; i++) {Â Â Â Â Â Â Â Â Â Â Â Â System.out.print(a[i] + " ");Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â System.out.println();Â Â Â Â }Â
    // Template formed so that sorting of any    // type variable is possible    public static void printArray(String[] a) {        for (int i = 0; i < a.length; i++) {            System.out.print(a[i] + " ");        }        System.out.println();    }Â
    public static void printArray(float[] a) {        for (int i = 0; i < a.length; i++) {            System.out.print(a[i] + " ");        }        System.out.println();    }         // Driver code    public static void main(String[] args) {        int n = 4;        int[] intArr = {2000, 456, -10, 0};        Arrays.sort(intArr);        printArray(intArr);Â
        String[] strArr = {"We do nothing",                           "Hi I have something",                           "Hello Join something!",                           "(Why to do work)"};        Arrays.sort(strArr);        printArray(strArr);Â
        float[] floatArr = {23.4f, 11.4f, -9.7f, 11.17f};        Arrays.sort(floatArr);        printArray(floatArr);    }}Â
// This code is contributed by shiv1o43g |
Python3
def printArray(a):Â Â Â Â for i in range(len(a)):Â Â Â Â Â Â Â Â print(a[i], end=" ")Â Â Â Â print()Â
def main():Â Â Â Â n = 4Â Â Â Â intArr = [2000, 456, -10, 0]Â Â Â Â intArr.sort()Â Â Â Â printArray(intArr)Â
    strArr = ["We do nothing",              "Hi I have something",              "Hello Join something!",              "(Why to do work)"]    strArr.sort()    printArray(strArr)Â
    floatArr = [23.4, 11.4, -9.7, 11.17]    floatArr.sort()    printArray(floatArr)Â
if __name__ == "__main__":Â Â Â Â main()Â
Â
# This code is contributed by shivhack999 |
C#
// C# program to sort array of any data types.using System;Â
public class MainClass{    // Template formed so that sorting of any    // type variable is possible    public static void PrintArray<T>(T[] arr)    {        foreach (T item in arr)        {            Console.Write(item + " ");        }        Console.WriteLine();    }Â
    // Driver code    public static void Main()    {        int[] intArr = { 2000, 456, -10, 0 };        Array.Sort(intArr);        PrintArray(intArr);Â
        string[] strArr = { "We do nothing",                        "Hi I have something",                        "Hello Join something!",                        "(Why to do work)" };        Array.Sort(strArr);        PrintArray(strArr);Â
        float[] floatArr = { 23.4f, 11.4f, -9.7f, 11.17f };        Array.Sort(floatArr);        PrintArray(floatArr);    }}Â
// This code is contributed by Utkarsh Kumar |
Javascript
<script>    // Javascript program to sort array of any data types.          function printArray(arr) {      for (let i = 0; i < arr.length; i++) {    document.write(arr[i] + " ");      }      document.write("<br>");    }         // Driver code    const intArr = [2000, 456, -10, 0];    intArr.sort((a, b) => a - b);    printArray(intArr);         const strArr = [      "We do nothing",      "Hi I have something",      "Hello Join something!",      "(Why to do work)"    ];    strArr.sort();    printArray(strArr);         const floatArr = [23.4, 11.4, -9.7, 11.17];    floatArr.sort();    printArray(floatArr);         // This code is contributed by Pushpesh Raj.</script> |
Output
-10 0 456 2000 (Why to do work) Hello Join something! Hi I have something We do nothing -9.7 11.17 11.4 23.4
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



