Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An array of length N can contain values 1,2,3 ... N^2. Is it possible to sort in O(n) time?

Given an array of length N. It can contain values from ranging from 1 to N^2 (N squared) both inclusive, values are integral. Is it possible to sort this array in O(N) time? If possible how?

Edit: This is not a homework.

like image 391
riderchap Avatar asked Nov 21 '10 14:11

riderchap


2 Answers

Write each integer in base N, that is each x can be represented as (x1, x2) with x = 1 + x1 + x2*N. Now you can sort it twice with counting sort, once on x1 and once on x2, resulting in the sorted array.

EDIT: As others mentioned below, sorting on each 'digit' separately like this is is called a radix sort. Sorting on each digit with counting sort takes O(N) time and O(N) space (in this particular case). Since we repeat it exactly twice, this gives a total running time of O(N).

like image 106
Yakov Galka Avatar answered Oct 17 '22 06:10

Yakov Galka


Yes, you can, using radix sort with N buckets and two passes. Basically, you treat the numbers as having 2 digits in base N.

like image 35
svick Avatar answered Oct 17 '22 06:10

svick