Open In App

Program for sorting variables of any data type

Last Updated : 07 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of any data type, the task is to sort the given array without using in-built sorting functions.

Examples:

Input: arr[] = [64, 34, 25, 12, 22, 11, 90]
Output: 11 12 22 25 34 64 90

Input: arr[] = ["banana", "apple", "orange", "grape", "kiwi"]
Output: apple banana grape kiwi orange

Input: arr[] = [55.2, 10.6, 44.1, 36.0]
Output: 10.6 36 44.1 55.2

Using In-Built Sorting Functions - O(n log n) time and O(1) space

The idea is to use language specific in-built sorting functions to sort the array. Most of the modern statically typed programming languages either provide generic functions (For example C++ and Java) where we provide data type as input. In dynamically typed languages, we can anyways call functions for any data type that supports comparison.

C++
Java Python C# JavaScript

Output
11 12 22 25 34 64 90 
apple banana grape kiwi orange 

Writing Your Method - Example using Bubble Sort - O(n^2) time and O(1) space

The idea is to use "generic programming" or "parametric polymorphism" to create a single sorting algorithm that works with any data type.

For each language implementation:

  1. C++: Uses template functions (template<typename T>) to create type-agnostic code that works with any comparable data type.
  2. Java: Uses generic classes/methods (<T extends Comparable<T>>) to ensure type safety while allowing multiple data types.
  3. Python: Uses duck typing to handle different data types without explicit type declarations.
  4. C#: Uses generic methods/classes (<T> where T : IComparable<T>) to create reusable, type-safe algorithms.
  5. JavaScript: Uses its dynamic typing with implicit type conversion for operations on different data types.
CPP
Java Python C# JavaScript

Output
11 12 22 25 34 64 90 
apple banana grape kiwi orange 


Next Article
Article Tags :
Practice Tags :

Similar Reads