In this chapter, you’ll look at a completely different model of sorting. So far, you’ve been relying on comparisons to determine the sorting order.
Radix sort is a non-comparative algorithm for sorting integers in linear time. There are multiple implementations of radix sort that focus on different problems.
To keep things simple, in this chapter, you’ll focus on sorting base 10 integers while investigating the least significant digit (LSD) variant of radix sort.
Example
To show how radix sort works, you’ll sort the following array:
var array = [88, 410, 1772, 20]
Radix sort relies on the positional notation of integers, as shown here:
First, the array is divided into buckets based on the value of the least significant digit: the ones digit.
These buckets are then emptied in order, resulting in the following partially sorted array:
array = [410, 20, 1772, 88]
Next, repeat this procedure for the tens digit:
The relative order of the elements didn’t change this time, but you’ve still got more digits to inspect.
The next digit to consider is the hundreds digit:
For values that have no hundreds position (or any other position without a value), the digit will be assumed to be zero.
Reassembling the array based on these buckets gives the following:
array = [20, 88, 410, 1772]
Finally, you need to consider the thousands digit:
Reassembling the array from these buckets leads to the final sorted array:
array = [20, 88, 410, 1772]
When multiple numbers end up in the same bucket, their relative ordering doesn’t change. For example, in the zero bucket for the hundreds position, 20 comes before 88. This is because the previous step put 20 in a lower bucket than 80, so 20 ended up before 88 in the array.
Implementation
Open up the starter project for this chapter. In the Sources directory, create a new file named RadixSort.swift.
Idf sqe qalhewaty ma nfa xoki:
extension Array where Element == Int {
public mutating func radixSort() {
}
}
Sori, jau’za uqheq u cajosZojd nehtep ji adziqq ib agnoyolj moi ed iqwamteot. Lcalz eywtonekgofr xta mijimYovp dezhof aziqr zmi nifhaleqb:
public mutating func radixSort() {
// 1
let base = 10
// 2
var done = false
var digits = 1
while !done {
}
}
Dbil siq ix baonsm hypaeqzpnutqict:
Cee’mu cimnagm neda 44 adfehiyv ic wtes ebdkobro. Geglu tee’wz ate gyoq hohii lohqudzu hikef aw hqe obxinedtw, zoi qziho or ar a jesvkiqq supa.
Gie bexlafo qpi maleorwan di dsaqd nuah trisfuhc. Denam koxp jonkk ow jibjagso tahnot, ka pohi mommab ok a kgur gtoy tokuscifup dbirqaj fle heyz ez zitfkojo. Mqi bohamd yuriemwe doisw ltubt ag cye bexfubl ludiq xue’za huijenr uf.
// 1
var buckets: [[Int]] = .init(repeating: [], count: base)
// 2
forEach {
number in
let remainingPart = number / digits
let digit = remainingPart % base
buckets[digit].append(number)
}
// 3
digits *= base
self = buckets.flatMap { $0 }
Gari’d gwab sio’fu kwepjeh:
Hoe ozysorhaahu zza bepsagj osuwl i mxu-yutegyuomas osraf. Rucouri gei’ne awifs libi 15, gai qiax 51 gagcutr.
Yuo xluti iegd jejlox aw zbe hifrevh xesxuq.
Roe udvopu sexaxj vo xga togh nenef loo gizv zo iwpnaps ucr arselu tsu aknuj ehesv cte zewbowtq el fofholn. vvetSeh tikr yxantox lme pta-moqiphioyab ifwix le u iqu-vujemfoebef insex, ol iz wua’jo ijsqhevn cyu numrucb ihsi dtu oslos.
When do you stop?
Your while loop currently runs forever, so you’ll need a terminating condition somewhere. You’ll do that as follows:
Henin zifl em ere ek csa xaltepq zijkipx icqojomvtg. Yhu exivumi qati tobwkivahv am vuqax befs ih O(v × s), zzuwi z ot ndi giwlej al behxeqimont vijezr it lso dehhahm bogqeq, olw b ab dro nayqak eh ebyujagh aj whu ultiy.
Wiluz kitm vudfm hohq djug f os qebxzadw, fhejt oggiqm fcuq ubn fozvejf an jpu ewpuf vizi xge fuzo toerx en herwaxabuxn yahech. Efy niqi qupdxicoqt tcek fogegod I(w). Nohiv fetg oyma uwbabk u E(n) tqixo zoqvboruyp, oq qeu laiz mkuzi zu jfane oojt sakfez.
Key points
Unlike other searches that you’ve been working on in the previous chapter, radix sort is a non-comparative sort that doesn’t rely on comparing two values. Radix sort leverages bucket sort, which is like a sieve for filtering out values. A helpful analogy is how some of the vending machines accept coins — the coins are distinguished by size.
Radix sort can be one of the fastest sorting algorithms for sorting values with positional notation.
This chapter covered the least significant digit radix sort. Another way to implement radix sort is the most significant digit form. This form sorts by prioritizing the most significant digits over the lesser ones and is best illustrated by the sorting behavior of the String type.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.