Skip to content
NorscodeNorscode

std.sortering

ReferenceBy the Norscode project

std.sortering sorts lists of numbers and text. The module contains several classic algorithms — bubble, insertion and selection sort among them — in separate variants for liste_heltall and liste_tekst.

std.sortering sorts lists of numbers and text. The module contains several classic algorithms — bubble, insertion and selection sort among them — in separate variants for liste_heltall and liste_tekst.

For ordinary use you just pick one of them; they give the same result. That there are several is both practical and educational: each algorithm is written out on its own, so the module is a good place to read how sorting actually works under the hood.

When to use it

Use std.sortering when you need to order a list. For most needs you pick one function and are done. The module is also a good place to learn how the different algorithms work, since each of them is written out separately.

Getting started

bruk std.sortering som sort

funksjon start() -> heiltall {
    la tall = [5, 2, 9, 1, 7]
    sort.boble(tall)          // tall is now [1, 2, 5, 7, 9]
    skriv(tekst(tall[0]))     // "1"
    returner 0
}

boble sorts the list in place — after the call tall itself is sorted, and you need no new variable.

The functions

Each algorithm comes in two variants: one for numbers (boble, innsett, utval …) and one for text with a _tekst suffix. All sort the list in place and give the same final result; they differ only in how they get there.

  • boble(l: liste_heltall) -> heltall — Bubble-sorts a liste_heltall ascending, in place.
  • boble_tekst(l: liste_tekst) -> heltall — Bubble-sorts a liste_tekst, in place.
  • innsett(l: liste_heltall) -> heltall — Insertion-sorts a liste_heltall, in place.
  • innsett_tekst(l: liste_tekst) -> heltall — Insertion-sorts a liste_tekst, in place.
  • utval(l: liste_heltall) -> heltall — Selection-sorts a liste_heltall, in place.
  • flett(l: liste_heltall) -> heltall
  • kvikk(l: liste_heltall) -> heltall
  • skall(l: liste_heltall) -> heltall
  • radix(l: liste_heltall) -> heltall
  • heap(l: liste_heltall) -> heltall
  • tim(l: liste_heltall) -> heltall
  • sortert(l: liste_heltall) -> liste_heltall
  • sortert_tekst(l: liste_tekst) -> liste_tekst
  • er_sortert(l: liste_heltall) -> bool
  • er_sortert_synkande(l: liste_heltall) -> bool

Good to know

  • The sort happens in place: the list you pass in is itself sorted after the call.
  • Choose the text variants (boble_tekst, innsett_tekst, utval_tekst) for liste_tekst.
  • For small lists the choice of algorithm makes no practical difference; they are there as much to learn from as to use.

std.sortering is one of the modules in the standard library. Everything ships with the runtime — no installation, no external dependencies. See also Documentation for the language and the runtime.

Related

Back to the overview