Sort n numbers in range from 0 to n^2 - 1 in linear time
Last Updated :
13 Aug, 2024
Given an array of numbers of size n. It is also given that the array elements are in the range from 0 to n2 - 1. Sort the given array in linear time.
Examples:
Since there are 5 elements, the elements can be from 0 to 24.
Input: arr[] = {0, 23, 14, 12, 9}
Output: arr[] = {0, 9, 12, 14, 23}
Since there are 3 elements, the elements can be from 0 to 8.
Input: arr[] = {7, 0, 2}
Output: arr[] = {0, 2, 7}
Solution: If we use Counting Sort, it would take O(n^2) time as the given range is of size n^2. Using any comparison-based sorting like Merge Sort, Heap Sort, .. etc would take O(nLogn) time.
Now the question arises how to do this in 0(n)? Firstly, is it possible? Can we use the data given in the question? n numbers in the range from 0 to n2 - 1?
The idea is to use Radix Sort. Following is the standard Radix Sort algorithm.
1) Do following for each digit i where i varies from least
significant digit to the most significant digit.
…………..a) Sort input array using counting sort (or any stable sort) according to the i’th digit
Let there be d digits in input integers. Radix Sort takes O(d*(n+b)) time where b is the base for representing numbers, for example, for a decimal system, b is 10. Since n2-1 is the maximum possible value, the value of d would be O(logb(n)). So overall time complexity is O((n+b)*O(logb(n)). Which looks more than the time complexity of comparison-based sorting algorithms for a large k. The idea is to change base b. If we set b as n, the value of O(logb(n)) becomes O(1) and overall time complexity becomes O(n).
arr[] = {0, 10, 13, 12, 7}
Let us consider the elements in base 5. For example 13 in
base 5 is 23, and 7 in base 5 is 12.
arr[] = {00(0), 20(10), 23(13), 22(12), 12(7)}
After first iteration (Sorting according to the last digit in
base 5), we get.
arr[] = {00(0), 20(10), 12(7), 22(12), 23(13)}
After second iteration, we get
arr[] = {00(0), 12(7), 20(10), 22(12), 23(13)}
Following is the implementation to sort an array of size n where elements are in range from 0 to n2 - 1.
C++
#include<iostream>
using namespace std;
// A function to do counting sort of arr[] according to
// the digit represented by exp.
int countSort(int arr[], int n, int exp)
{
int output[n]; // output array
int i, count[n] ;
for (int i=0; i < n; i++)
count[i] = 0;
// Store count of occurrences in count[]
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%n ]++;
// Change count[i] so that count[i] now contains actual
// position of this digit in output[]
for (i = 1; i < n; i++)
count[i] += count[i - 1];
// Build the output array
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%n] - 1] = arr[i];
count[(arr[i]/exp)%n]--;
}
// Copy the output array to arr[], so that arr[] now
// contains sorted numbers according to current digit
for (i = 0; i < n; i++)
arr[i] = output[i];
}
// The main function to that sorts arr[] of size n using Radix Sort
void sort(int arr[], int n)
{
// Do counting sort for first digit in base n. Note that
// instead of passing digit number, exp (n^0 = 1) is passed.
countSort(arr, n, 1);
// Do counting sort for second digit in base n. Note that
// instead of passing digit number, exp (n^1 = n) is passed.
countSort(arr, n, n);
}
// A utility function to print an array
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver program to test above functions
int main()
{
// Since array size is 7, elements should be from 0 to 48
int arr[] = {40, 12, 45, 32, 33, 1, 22};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Given array is\n";
printArr(arr, n);
sort(arr, n);
cout << "\nSorted array is\n";
printArr(arr, n);
return 0;
}
Java
// Java program to sort an array of size n where elements are
// in range from 0 to n^2 – 1.
import java.io.*;
public class Sort1ToN2
{
// A function to do counting sort of arr[] according to
// the digit represented by exp.
void countSort(int arr[], int n, int exp)
{
int output[] = new int[n]; // output array
int i, count[] = new int[n] ;
for (i=0; i < n; i++)
count[i] = 0;
// Store count of occurrences in count[]
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%n ]++;
// Change count[i] so that count[i] now contains actual
// position of this digit in output[]
for (i = 1; i < n; i++)
count[i] += count[i - 1];
// Build the output array
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%n] - 1] = arr[i];
count[(arr[i]/exp)%n]--;
}
// Copy the output array to arr[], so that arr[] now
// contains sorted numbers according to current digit
for (i = 0; i < n; i++)
arr[i] = output[i];
}
// The main function to that sorts arr[] of size n using Radix Sort
void sort(int arr[], int n)
{
// Do counting sort for first digit in base n. Note that
// instead of passing digit number, exp (n^0 = 1) is passed.
countSort(arr, n, 1);
// Do counting sort for second digit in base n. Note that
// instead of passing digit number, exp (n^1 = n) is passed.
countSort(arr, n, n);
}
// A utility function to print an array
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(arr[i]+" ");
}
// Driver program to test above functions
public static void main(String args[])
{
Sort1ToN2 ob = new Sort1ToN2();
// Since array size is 7, elements should be from 0 to 48
int arr[] = {40, 12, 45, 32, 33, 1, 22};
int n = arr.length;
System.out.println("Given array");
ob.printArr(arr, n);
ob.sort(arr, n);
System.out.println("\nSorted array");
ob.printArr(arr, n);
}
}
/*This code is contributed by Rajat Mishra */
Python3
# Python3 the implementation to sort an
# array of size n
# A function to do counting sort of arr[]
# according to the digit represented by exp.
def countSort(arr, n, exp):
output = [0] * n # output array
count = [0] * n
for i in range(n):
count[i] = 0
# Store count of occurrences in count[]
for i in range(n):
count[ (arr[i] // exp) % n ] += 1
# Change count[i] so that count[i] now contains
# actual position of this digit in output[]
for i in range(1, n):
count[i] += count[i - 1]
# Build the output array
for i in range(n - 1, -1, -1):
output[count[ (arr[i] // exp) % n] - 1] = arr[i]
count[(arr[i] // exp) % n] -= 1
# Copy the output array to arr[], so that
# arr[] now contains sorted numbers according
# to current digit
for i in range(n):
arr[i] = output[i]
# The main function to that sorts arr[] of
# size n using Radix Sort
def sort(arr, n) :
# Do counting sort for first digit in base n.
# Note that instead of passing digit number,
# exp (n^0 = 1) is passed.
countSort(arr, n, 1)
# Do counting sort for second digit in base n.
# Note that instead of passing digit number,
# exp (n^1 = n) is passed.
countSort(arr, n, n)
# Driver Code
if __name__ =="__main__":
# Since array size is 7, elements should
# be from 0 to 48
arr = [40, 12, 45, 32, 33, 1, 22]
n = len(arr)
print("Given array is")
print(*arr)
sort(arr, n)
print("Sorted array is")
print(*arr)
# This code is contribute by
# Shubham Singh(SHUBHAMSINGH10)
C#
// C# program to sort an array of
// size n where elements are
// in range from 0 to n^2 – 1.
using System;
class GFG {
// A function to do counting
// sort of arr[] according to
// the digit represented by exp.
static void countSort(int[] arr,
int n,
int exp)
{
// output array
int[] output = new int[n];
int[] count = new int[n] ;
int i;
for (i = 0; i < n; i++)
count[i] = 0;
// Store count of
// occurrences in count[]
for (i = 0; i < n; i++)
count[(arr[i] / exp) % n ]++;
// Change count[i] so that
// count[i] now contains actual
// position of this digit in output[]
for (i = 1; i < n; i++)
count[i] += count[i - 1];
// Build the output array
for (i = n - 1; i >= 0; i--)
{
output[count[(arr[i] /
exp) % n] - 1] = arr[i];
count[(arr[i] / exp) % n]--;
}
// Copy the output array to
// arr[], so that arr[] now
// contains sorted numbers
// according to current digit
for (i = 0; i < n; i++)
arr[i] = output[i];
}
// The main function to that
// sorts arr[] of size n
// using Radix Sort
static void sort(int[] arr, int n)
{
// Do counting sort for first
// digit in base n. Note that
// instead of passing digit number,
// exp (n^0 = 1) is passed.
countSort(arr, n, 1);
// Do counting sort for second
// digit in base n. Note that
// instead of passing digit number,
// exp (n^1 = n) is passed.
countSort(arr, n, n);
}
// A utility function
// to print an array
static void printArr(int[] arr, int n)
{
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
// Driver Code
static public void Main ()
{
// Since array size is 7,
// elements should be
// from 0 to 48
int[] arr = {40, 12, 45, 32, 33, 1, 22};
int n = arr.Length;
Console.WriteLine("Given array");
printArr(arr, n);
sort(arr, n);
Console.WriteLine("\nSorted array");
printArr(arr, n);
}
}
// This code is contributed by Ajit.
JavaScript
<script>
// Javascript program to sort an array of
// size n where elements are
// in range from 0 to n^2 – 1.
// A function to do counting
// sort of arr[] according to
// the digit represented by exp.
function countSort(arr, n, exp)
{
// Output array
let output = new Array(n);
let count = new Array(n);
count.fill(0);
output.fill(0);
let i;
for(i = 0; i < n; i++)
count[i] = 0;
// Store count of
// occurrences in count[]
for(i = 0; i < n; i++)
count[parseInt(arr[i] / exp, 10) % n ]++;
// Change count[i] so that
// count[i] now contains actual
// position of this digit in output[]
for(i = 1; i < n; i++)
count[i] += count[i - 1];
// Build the output array
for (i = n - 1; i >= 0; i--)
{
output[count[parseInt(
arr[i] / exp, 10) % n] - 1] = arr[i];
count[parseInt(arr[i] / exp, 10) % n]--;
}
// Copy the output array to
// arr[], so that arr[] now
// contains sorted numbers
// according to current digit
for(i = 0; i < n; i++)
arr[i] = output[i];
}
// The main function to that
// sorts arr[] of size n
// using Radix Sort
function sort(arr, n)
{
// Do counting sort for first
// digit in base n. Note that
// instead of passing digit number,
// exp (n^0 = 1) is passed.
countSort(arr, n, 1);
// Do counting sort for second
// digit in base n. Note that
// instead of passing digit number,
// exp (n^1 = n) is passed.
countSort(arr, n, n);
}
// A utility function
// to print an array
function printArr(arr, n)
{
for(let i = 0; i < n; i++)
document.write(arr[i] + " ");
}
// Driver code
// Since array size is 7,
// elements should be
// from 0 to 48
let arr = [ 40, 12, 45, 32, 33, 1, 22 ];
let n = arr.length;
document.write("Given array" + "</br>");
printArr(arr, n);
sort(arr, n);
document.write("</br>Sorted array" + "</br>");
printArr(arr, n);
// This code is contributed by divyesh072019
</script>
OutputGiven array is
40 12 45 32 33 1 22
Sorted array is
1 12 22 32 33 40 45
Time Complexity: O(n).
Auxiliary Space: O(n)
How to sort if the range is from 1 to n2?
If the range is from 1 to n2, the above process can not be directly applied, it must be changed. Consider n = 100 and range from 1 to 10000. Since the base is 100, a digit must be from 0 to 99 and there should be 2 digits in the numbers. But the number 10000 has more than 2 digits. So to sort numbers in a range from 1 to n2, we can use the following process.
1) Subtract all numbers by 1.
2) Since the range is now 0 to n2, do counting sort twice as done in the above implementation.
3) After the elements are sorted, add 1 to all numbers to obtain the original numbers.
How to sort if the range is from 0 to n^3 -1?
Since there can be 3 digits in base n, we need to call counting sort 3 times.
Similar Reads
Radix Sort - Data Structures and Algorithms Tutorials
Radix Sort is a linear sorting algorithm that sorts elements by processing them digit by digit. It is an efficient sorting algorithm for integers or strings with fixed-size keys. Rather than comparing elements directly, Radix Sort distributes the elements into buckets based on each digit's value. By
15+ min read
C Program For Radix Sort
Radix Sort is a linear sorting algorithm that sorts elements by processing them digit by digit. It is an efficient sorting algorithm for integers or strings with fixed-size keys. Rather than comparing elements directly, Radix Sort distributes the elements into buckets based on each digitâs value. By
3 min read
Radix Sort - Python
Radix Sort is a linear sorting algorithm that sorts elements by processing them digit by digit. It is an efficient sorting algorithm for integers or strings with fixed-size keys. Rather than comparing elements directly, Radix Sort distributes the elements into buckets based on each digitâs value. By
3 min read
Java Program for Radix Sort
The Radix Sort Algorithm Do the following for each digit i where i varies from the least significant digit to the most significant digit.Sort input array using counting sort (or any stable sort) according to the ith digit. java // Radix sort Java implementation import java.io.*; import java.util.*;
3 min read
3-Way Radix Quicksort in Java
Basically, as the name suggests that 3-Way Radix Quicksort is a combination of both radix and 3-way quicksort. It is a hybrid sort which is in between of both radix and 3-way quicksort. This algorithm is mainly used to sort strings. The main idea behind the radix sort is to use the digits (beginning
9 min read
MSD( Most Significant Digit ) Radix Sort
In this article, two types of Radix Sort are discussed: LSD Radix Sort: It starts sorting from the end of strings (the Least significant digit).MSD Radix Sort: It starts sorting from the beginning of strings (the Most significant digit).In this article, the task is to discuss the MSD Radix Sort and
15+ min read
Sort n numbers in range from 0 to n^2 - 1 in linear time
Given an array of numbers of size n. It is also given that the array elements are in the range from 0 to n2 - 1. Sort the given array in linear time.Examples: Since there are 5 elements, the elements can be from 0 to 24.Input: arr[] = {0, 23, 14, 12, 9}Output: arr[] = {0, 9, 12, 14, 23}Since there a
12 min read
How to efficiently sort a big list dates in 20's
Given a big list of dates in '20s, how to efficiently sort the list. Example: Input: Date arr[] = {{20, 1, 2014}, {25, 3, 2010}, { 3, 12, 2000}, {18, 11, 2001}, {19, 4, 2015}, { 9, 7, 2005}} Output: Date arr[] = {{ 3, 12, 2000}, {18, 11, 2001}, { 9, 7, 2005}, {25, 3, 2010}, {20, 1, 2014}, {19, 4, 20
11 min read
Radix Sort vs Bucket Sort
We have two standard sorting algorithms, named bucket sort and radix sort. They both share differences and similarities. Letâs explore some similarities, differences, advantages, and disadvantages here in more detail. Bucket Sort: Bucket sort is a sorting algorithm in which the elements are separate
6 min read