Introsort

Introsort
ClassSorting algorithm
Data structureArray
Worst-case performanceO(n log n)
Average performanceO(n log n)
Optimalyes

Introsort or introspective sort is a hybrid sorting algorithm that provides both fast average performance and (asymptotically) optimal worst-case performance. It begins with quicksort, it switches to heapsort when the recursion depth exceeds a level based on (the logarithm of) the number of elements being sorted and it switches to insertion sort when the number of elements is below some threshold. This combines the good parts of the three algorithms, with practical performance comparable to quicksort on typical data sets and worst-case O(n log n) runtime due to the heap sort. Since the three algorithms it uses are comparison sorts, it is also a comparison sort.

Introsort was invented by David Musser in Musser (1997), in which he also introduced introselect, a hybrid selection algorithm based on quickselect (a variant of quicksort), which falls back to median of medians and thus provides worst-case linear complexity, which is optimal. Both algorithms were introduced with the purpose of providing generic algorithms for the C++ Standard Library which had both fast average performance and optimal worst-case performance, thus allowing the performance requirements to be tightened.[1] Introsort is in-place and a non-stable algorithm.

Pseudocode

If a heapsort implementation and partitioning functions of the type discussed in the quicksort article are available, the introsort can be described succinctly as

procedure sort(A : array):
    maxdepth ← ⌊log2(length(A))⌋ × 2
    introsort(A, maxdepth)

procedure introsort(A, maxdepth):
    n ← length(A)
    if n < 16:
        insertionsort(A)
    else if maxdepth = 0:
        heapsort(A)
    else:
        p ← partition(A)  // assume this function does pivot selection, p is the final position of the pivot
        introsort(A[1:p-1], maxdepth - 1)
        introsort(A[p+1:n], maxdepth - 1)

The factor 2 in the maximum depth is arbitrary; it can be tuned for practical performance. A[i:j] denotes the array slice of items i to j including both A[i] and A[j]. The indices are assumed to start with 1 (the first element of the A array is A[1]).

Analysis

In quicksort, one of the critical operations is choosing the pivot: the element around which the list is partitioned. The simplest pivot selection algorithm is to take the first or the last element of the list as the pivot, causing poor behavior for the case of sorted or nearly sorted input. Niklaus Wirth's variant uses the middle element to prevent these occurrences, degenerating to O(n2) for contrived sequences. The median-of-3 pivot selection algorithm takes the median of the first, middle, and last elements of the list; however, even though this performs well on many real-world inputs, it is still possible to contrive a median-of-3 killer list that will cause dramatic slowdown of a quicksort based on this pivot selection technique.

Musser reported that on a median-of-3 killer sequence of 100,000 elements, introsort's running time was 1/200 that of median-of-3 quicksort. Musser also considered the effect on caches of Sedgewick's delayed small sorting, where small ranges are sorted at the end in a single pass of insertion sort. He reported that it could double the number of cache misses, but that its performance with double-ended queues was significantly better and should be retained for template libraries, in part because the gain in other cases from doing the sorts immediately was not great.

Implementations

Introsort or some variant is used in a number of standard library sort functions, including some C++ sort implementations.

The June 2000 SGI C++ Standard Template Library stl_algo.h implementation of unstable sort uses the Musser introsort approach with the recursion depth to switch to heapsort passed as a parameter, median-of-3 pivot selection and the Knuth final insertion sort pass for partitions smaller than 16.

The GNU Standard C++ library is similar: uses introsort with a maximum depth of 2×log2 n, followed by an insertion sort on partitions smaller than 16.[2]

LLVM libc++ also uses introsort with a maximum depth of 2×log2 n, however the size limit for insertion sort is different for different data types (30 if swaps are trivial, 6 otherwise). Also, arrays with sizes up to 5 are handled separately.[3] Kutenin (2022) provides an overview for some changes made by LLVM, with a focus on the 2022 fix for quadraticness.[4]

The Microsoft .NET Framework Class Library, starting from version 4.5 (2012), uses introsort instead of simple quicksort.[5]

Go uses a modification of introsort: for slices of 12 or less elements it uses insertion sort, and for larger slices it uses pattern-defeating quicksort and more advanced median of three medians for pivot selection.[6] Prior to version 1.19 it used shell sort for small slices.

Java, starting from version 14 (2020), uses a hybrid sorting algorithm that uses merge sort for highly structured arrays (arrays that are composed of a small number of sorted subarrays) and introsort otherwise to sort arrays of ints, longs, floats and doubles.[7]

Variants

pdqsort

Pattern-defeating quicksort (pdqsort) is a variant of introsort incorporating the following improvements:[8]

  • Median-of-three pivoting,
  • "BlockQuicksort" partitioning technique to mitigate branch misprediction penalities,
  • Linear time performance for certain input patterns (adaptive sort),
  • Use element shuffling on bad cases before trying the slower heapsort.
  • Improved adaptivity for low-cardinality inputs

pdqsort is used by Rust, GAP,[9] and the C++ library Boost.[10]

fluxsort

fluxsort is a stable variant of introsort incorporating the following improvements:[11]

  • branchless sqrt(n) pivoting
  • Flux partitioning technique for stable partially-in-place partitioning
  • Significantly improved smallsort by utilizing branchless bi-directional parity merges
  • A fallback to quadsort, a branchless bi-directional mergesort, significantly increasing adaptivity for ordered inputs

Improvements introduced by fluxsort and its unstable variant, crumsort, were adopted by crumsort-rs, glidesort, ipnsort, and driftsort. The overall performance increase on random inputs compared to pdqsort is around 50%.[12][13][14][15][16]

References

  1. ^ "Generic Algorithms", David Musser
  2. ^ libstdc++ Documentation: Sorting Algorithms
  3. ^ libc++ source code: sort
  4. ^ Kutenin, Danila (20 April 2022). "Changing std::sort at Google's Scale and Beyond". Experimental chill.
  5. ^ Array.Sort Method (Array)
  6. ^ Go 1.20.3 source code
  7. ^ Java 14 source code
  8. ^ Peters, Orson R. L. (2021). "orlp/pdqsort: Pattern-defeating quicksort". GitHub. arXiv:2106.05123.
  9. ^ "slice.sort_unstable(&mut self)". Rust. The current algorithm is based on pattern-defeating quicksort by Orson Peters, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior.
  10. ^ Lammich, Peter (2020). Efficient Verified Implementation of Introsort and Pdqsort. IJCAR 2020: Automated Reasoning. Vol. 12167. pp. 307–323. doi:10.1007/978-3-030-51054-1_18.
  11. ^ van den Hoven, Igor (2021). "fluxsort". GitHub.
  12. ^ van den Hoven, Igor (2022). "crumsort". GitHub.
  13. ^ Tiselice, Dragoș (2022). "crumsort-rs". GitHub.
  14. ^ Peters, Orson (2023). "Glidesort: Efficient In-Memory Adaptive Stable Sorting on Modern Hardware".
  15. ^ Bergdoll, Lukas (2024). "ipnsort: an efficient, generic and robust unstable sort implementation".
  16. ^ Bergdoll, Lukas (2024). "driftsort: an efficient, generic and robust stable sort implementation".

General

Read other articles:

Questio de primo cognito Marcantonio Zimara (sk. 1460–1532) adalah seorang filsuf Italia Life Ia lahir di Galatina (sekarang Lecce) dan belajar filsafat sejak 1497 di Universitas Padova. Ia diajarkan oleh Agostino Nifo dan Pietro Pomponazzi. Lalu ia mengajarkan ilmu logika sambil belajar kedokteran di Padova (1501–1505), dan pada 1509 menjadi profesor filsafat alam. Selama 1509–1518 Zimara tinggal di Galatina, lalu ia mengajar Salerno (1518–1522), Napoli (1522–1523), lalu kembali ke...

 

  لمعانٍ أخرى، طالع إيستون (توضيح). إيستون     الإحداثيات 42°01′28″N 71°07′45″W / 42.024444444444°N 71.129166666667°W / 42.024444444444; -71.129166666667  تاريخ التأسيس 1694  تقسيم إداري  البلد الولايات المتحدة[1][2]  التقسيم الأعلى مقاطعة بريستول  خصائص جغرافية  المس...

 

French rugby union player Rugby playerSylvain NicolasDate of birth (1987-06-21) 21 June 1987 (age 36)Place of birthBourgoin-Jallieu, FranceHeight1.88 m (6 ft 2 in)Weight102 kg (16 st 1 lb)Rugby union careerPosition(s) FlankerSenior careerYears Team Apps (Points)2007–20102010–20132013- BourgoinToulouseStade Français 544658 (15)(10)(15) Correct as of 11 October 2014 Sylvain Nicolas (born 21 June 1987) is a French rugby union player. His position is f...

أولاد عبد السلام تقسيم إداري البلد المغرب  الجهة فاس مكناس الإقليم تاونات الدائرة تيسة الجماعة القروية عين معطوف المشيخة جعافرةالعليا السكان التعداد السكاني 272 نسمة (إحصاء 2004)   • عدد الأسر 47 معلومات أخرى التوقيت ت ع م±00:00 (توقيت قياسي)[1]،  وت ع م+01:00 (توقيت صيفي) ...

 

Це іберійські ім'я та прізвище. Перше (батькове) прізвище цієї особи Родрігес, а друге (материне) прізвище Ібарра. Хуан Карлос Родрігес Ібарраісп. Juan Carlos Rodríguez Ibarra Народився 19 січня 1948(1948-01-19) (75 років)Мерида, ІспаніяКраїна  ІспаніяДіяльність політик, senior lecturerAlma mater Севі...

 

ThirteenPoster film ThirteenSutradara Catherine Hardwicke Produser Jeff Levy-Hinte Michael London Ditulis oleh Catherine Hardwicke Nikki Reed PemeranHolly HunterEvan Rachel WoodNikki ReedPenata musikMark MothersbaughSinematograferElliot DavisPenyuntingNancy RichardsonPerusahaanproduksiWorking Title FilmsAntidote Films[1]DistributorSearchlight PicturesTanggal rilis 17 Januari 2003 (2003-01-17) (Festival Film Sundance) 20 Agustus 2003 (2003-08-20) (Amerika Serika...

Inter Miami CFFotbollsklubb GrundinformationGrundad29 januari 2018 (5 år sedan)Fullständigt namnClub Internacional de Fútbol MiamiSmeknamnThe HeronsLigaMajor League SoccerKonferensEastern ConferenceOrt Miami, Florida, USAHemmaarenaLockhart Stadium(kapacitet: 18 000)Klubbfärg(er)              Farmarklubb(ar) Fort Lauderdale CFNyckelpersonerÄgare David Beckham Jorge Mas Jose Mas[1]OrdförandeDavid Beckham[1]VDJ...

 

Pour les articles homonymes, voir Le Trône de fer. Game of ThronesLe Trône de ferDéveloppeur Cyanide StudioÉditeur Focus Home Interactive (EU)Atlus (USA)Date de sortie 15 mai 2012Franchise Liste de jeux vidéo Le Trône de ferGenre Jeu de rôleMode de jeu SoloPlate-forme Microsoft Windows, PlayStation 3, Xbox 360Langue FrancaiseMoteur Unreal Engine 3 (d)Version NTCÉvaluation BBFC : 15 ?ESRB : M ?PEGI : 18 ?Site web www.gameofthrones-thegame.commodifier - modifier le code -...

 

This article contains content that is written like an advertisement. Please help improve it by removing promotional content and inappropriate external links, and by adding encyclopedic content written from a neutral point of view. (October 2022) (Learn how and when to remove this template message) Victorious 22 (V22LA) is a Los Angeles–based fashion line specializing in denim and leather jackets, pants, purses, and accessories. V22 was started in 2010 by Frank Rodriguez and his wife Angela....

Visual arts produced during the European Renaissance Albrecht Dürer, Adam and Eve in the Prado Museum, 1507 Jan van Eyck, The Ghent Altarpiece: The Adoration of the Mystic Lamb (interior view), 1432 Titian, Sacred and Profane Love, c. 1513 – 1514, Galleria Borghese, Rome Piero della Francesca, The Baptism of Christ, c. 1450, National Gallery, London Renaissance art (1350 – 1620 AD[1]) is the painting, sculpture, and decorative arts of the period of European history known as the R...

 

1998 video game 1998 video gameFallout 2Developer(s)Black Isle StudiosPublisher(s)Interplay Productions[a]Producer(s)Eric DeMiltFeargus UrquhartDesigner(s)Feargus UrquhartMatthew J. NortonProgrammer(s)Jesse ReynoldsArtist(s)Gary PlatnerTramell Ray IsaacWriter(s)Mark O'GreenComposer(s)Mark MorganSeriesFalloutPlatform(s)WindowsMac OS XReleaseWindowsOctober 29, 1998[1]Mac OS XAugust 23, 2002[2]Genre(s)Role-playingMode(s)Single-player Fallout 2: A Post Nuclear Role Playing...

 

Zafarullah Khan JamaliPerdana Menteri Pakistan ke-15Masa jabatan23 November 2002 – 26 Juni 2004PresidenPervez MusharrafPendahuluPervez Musharraf (sebagai Ketua Eksekutif)Nawaz Sharif (sebagai Perdana Menteri)PenggantiChaudhry Shujaat HussainKetua Menteri BalochistanMasa jabatan9 November 1996 – 22 Februari 1997PenjabatGubernurImran Ullah KhanPendahuluZulfiqar Ali Khan MagsiPenggantiAkhtar MengalMasa jabatan23 Juni 1988 – 24 Desember 1988GubernurMuhammad MusaPe...

Santo Domingo Provincie in de Dominicaanse Republiek Situering Macroregio[1] Sureste Regio (Nr) Ozama (of: Metropolitana) (X) Coördinaten 19° 25′ NB, 69° 50′ WL Algemeen Oppervlakte 1302,20[2] km² Inwoners (2016) 2.702.028[3] (2075 inw./km²) Hoofdstad Santo Domingo Este ONE-code 32 ISO 3166-2 DO-32 Detailkaart Inplanting van de provincie (rood) in het land Foto's El Faro a Colón in Santo Domingo Este Portaal    Caraïben Santo Domingo is een...

 

Rejencja koszalińska (niem Regierungsbezirk Köslin, w XIX wieku Regierungsbezirk Cöslin) – prusko-niemiecka jednostka podziału terytorialnego w latach 1816–1945, obejmująca dzisiejsze Pomorze Zachodnie. Stolicą był Köslin. Rejencja wchodziła w skład prowincji Pomorze. Historia Jednostka została wprowadzona w Prusach w latach 1815–1816 i istniała do 1945 jako pośredni szczebel administracji pomiędzy prowincją Pomorze ze stolicą w mieście Stettin a powiatami. Obecnie na j...

 

Rocketry and spacecraft propulsion research center Marshall Space Flight CenterAerial view of MSFC in 2016. Note that the building on the right has been demolished.[1]Agency overviewFormedJuly 1, 1960Preceding agencyRedstone ArsenalJurisdictionU.S. federal governmentHeadquartersRedstone Arsenal, Madison County, Alabama34°39′3″N 86°40′22″W / 34.65083°N 86.67278°W / 34.65083; -86.67278Employees6,000, including 2,300 civil servants[2]:̴...

Unincorporated community in the state of Idaho, United States Unincorporated community in Idaho, United StatesMurray, IdahoUnincorporated communityMurray Masonic Hall in 2021MurrayShow map of IdahoMurrayShow map of the United StatesCoordinates: 47°37′38″N 115°51′31″W / 47.62722°N 115.85861°W / 47.62722; -115.85861CountryUnited StatesStateIdahoCountyShoshoneElevation2,772 ft (845 m)Time zoneUTC-8 (Pacific (PST)) • Summer (DST)UTC-7 (PDT...

 

Bridal retailer David's BridalTypePrivateIndustrySpecialty RetailFounded1950; 73 years ago (1950)Fort Lauderdale, Florida, U.S.HeadquartersConshohocken, Pennsylvania, U.S.Number of locations195 stores in United States, Canada, and United Kingdom.Key peopleJames A. Marcum (Chief Executive Officer)Kelly Cook (President, Brand, Technology and Finance)Nancy Viall (President, Merchandising and Supply Chain)Bob Walker (Chief Operating Officer)Rob Cooper (Chief Financial Officer)An...

 

For other uses, see Walk Me Home (disambiguation). 2019 single by PinkWalk Me HomeSingle by Pinkfrom the album Hurts 2B Human ReleasedFebruary 20, 2019Genre Pop[1] Length2:58LabelRCASongwriter(s)Alecia MooreScott FriedmanNathaniel RuessProducer(s)Peter ThomasKyle MoormanPink singles chronology A Million Dreams (2018) Walk Me Home (2019) Can We Pretend (2019) Music videoWalk Me Home on YouTube Walk Me Home is a song recorded by American singer Pink for her eighth studio album, Hurts 2B...

Ford Fiesta S2000 Categoría RallyHomologación Super 2000Constructor FordDiseñador(es) M-SportEspecificaciones técnicasChasis Ford FiestaNombre motor Cilindrada 1997 ccCaja de cambios Marchas secuencial6Combustible GasolinaPalmarésDebut Rally de Montecarlo de 2010Poles -[editar datos en Wikidata] El Ford Fiesta S2000 es un automóvil de competición basado en el Ford Fiesta con homologación Super 2000. Fue diseñado por la empresa inglesa M-Sport para la marca Ford y ...

 

2002 remix album by Spacemonkeyz vs Gorillaz This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Laika Come Home – news · newspapers · books · scholar · JSTOR (October 2012) (Learn how and when to remove this template message) Laika Come HomeRemix album by Spacemonkeyz vs GorillazReleased1 July 2002Recorded2...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!