Tree sort

Tree sort
ClassSorting algorithm
Data structureArray
Worst-case performanceO(n²) (unbalanced) O(n log n) (balanced)
Best-case performanceO(n log n) [citation needed]
Average performanceO(n log n)
Worst-case space complexityΘ(n)
OptimalYes, if balanced

A tree sort is a sort algorithm that builds a binary search tree from the elements to be sorted, and then traverses the tree (in-order) so that the elements come out in sorted order.[1] Its typical use is sorting elements online: after each insertion, the set of elements seen so far is available in sorted order.

Tree sort can be used as a one-time sort, but it is equivalent to quicksort as both recursively partition the elements based on a pivot, and since quicksort is in-place and has lower overhead, tree sort has few advantages over quicksort. It has better worst case complexity when a self-balancing tree is used, but even more overhead.

Efficiency

Adding one item to a binary search tree is on average an O(log n) process (in big O notation). Adding n items is an O(n log n) process, making tree sorting a 'fast sort' process. Adding an item to an unbalanced binary tree requires O(n) time in the worst-case: When the tree resembles a linked list (degenerate tree). This results in a worst case of O(n²) time for this sorting algorithm. This worst case occurs when the algorithm operates on an already sorted set, or one that is nearly sorted, reversed or nearly reversed. Expected O(n log n) time can however be achieved by shuffling the array, but this does not help for equal items.

The worst-case behaviour can be improved by using a self-balancing binary search tree. Using such a tree, the algorithm has an O(n log n) worst-case performance, thus being degree-optimal for a comparison sort. However, tree sort algorithms require separate memory to be allocated for the tree, as opposed to in-place algorithms such as quicksort or heapsort. On most common platforms, this means that heap memory has to be used, which is a significant performance hit when compared to quicksort and heapsort[citation needed]. When using a splay tree as the binary search tree, the resulting algorithm (called splaysort) has the additional property that it is an adaptive sort, meaning that its running time is faster than O(n log n) for inputs that are nearly sorted.

Example

The following tree sort algorithm in pseudocode accepts a collection of comparable items and outputs the items in ascending order:

 STRUCTURE BinaryTree
     BinaryTree:LeftSubTree
     Object:Node
     BinaryTree:RightSubTree
 
 PROCEDURE Insert(BinaryTree:searchTree, Object:item)
     IF searchTree.Node IS NULL THEN
         SET searchTree.Node TO item
     ELSE
         IF item IS LESS THAN searchTree.Node THEN
             Insert(searchTree.LeftSubTree, item)
         ELSE
             Insert(searchTree.RightSubTree, item)
 
 PROCEDURE InOrder(BinaryTree:searchTree)
     IF searchTree.Node IS NULL THEN
         EXIT PROCEDURE
     ELSE
         InOrder(searchTree.LeftSubTree)
         EMIT searchTree.Node
         InOrder(searchTree.RightSubTree)
 
 PROCEDURE TreeSort(Collection:items)
     BinaryTree:searchTree
    
     FOR EACH individualItem IN items
         Insert(searchTree, individualItem)
    
     InOrder(searchTree)

In a simple functional programming form, the algorithm (in Haskell) would look something like this:

 data Tree a = Leaf | Node (Tree a) a (Tree a)

 insert :: Ord a => a -> Tree a -> Tree a
 insert x Leaf = Node Leaf x Leaf
 insert x (Node t y s)
     | x <= y = Node (insert x t) y s
     | x > y  = Node t y (insert x s)

 flatten :: Tree a -> [a]
 flatten Leaf = []
 flatten (Node t x s) = flatten t ++ [x] ++ flatten s

 treesort :: Ord a => [a] -> [a]
 treesort = flatten . foldr insert Leaf

In the above implementation, both the insertion algorithm and the retrieval algorithm have O(n²) worst-case scenarios.

References

  1. ^ McLuckie, Keith; Barber, Angus (1986). "Binary Tree Sort". Sorting routines for microcomputers. Basingstoke: Macmillan. ISBN 0-333-39587-5. OCLC 12751343.

Read other articles:

В Википедии есть статьи о других людях с фамилией Уорд. Уорд Леслиангл. Leslie Ward Лесли Уорд на фотографии Carl Vandyk, 1915 год Псевдонимы Spy и Drawl Дата рождения 21 ноября 1851(1851-11-21) Место рождения Лондон, Великобритания Дата смерти 15 мая 1922(1922-05-15) (70 лет) Место смерти Лондон, В...

 

Scottish law case over regnal number of Elizabeth II MacCormick v Lord AdvocateCourtInner House of the Court of SessionDecided30 July 1953Citation(s) 1953 SC 396 1953 SLT 255 [1953] 7 WLUK 166 [1953] CLY 597 Case historyAppealed fromOuter House of the Court of SessionCourt membershipJudge(s) sitting Lord President Lord Cooper Lord Carmont Lord Russell Keywords Judicial review Jurisdiction Queen Elizabeth II MacCormick v Lord Advocate 1953 SC 396 was a Scottish constitutional law case and Scot...

 

Esta página ou seção carece de contexto. Este artigo (ou seção) não possui um contexto definido, ou seja, não explica de forma clara e direta o tema que aborda. Se souber algo sobre o assunto edite a página/seção e explique de forma mais clara e objetiva o tema abordado. (Maio de 2022) Conjunto Muribeca foi um habitacional localizado no bairro da Muribeca, na cidade de Jaboatão dos Guararapes, Pernambuco. Números O Conjunto Habitacional Muribeca possuía originalmente 70 prédios,...

Chilean tennis player For other people named Luis Ayala, see Luis Ayala. In this Spanish name, the first or paternal surname is Ayala and the second or maternal family name is Salinas. Luis AyalaFull nameLuis Alberto AyalaCountry (sports) ChileResidenceUnited StatesBorn (1932-09-18) 18 September 1932 (age 91)Santiago, ChileHeight1.70 m (5 ft 7 in)Turned pro1961 (amateur from 1950)Retired1970PlaysRight-handed (one-handed backhand)SinglesCareer...

 

Із джунглів у джунгліангл. Jungle 2 JungleЖанр кінокомедіяРежисер Джон Пасквінd[1][2][3]Продюсер Браян РейліdСценарист Брюс Евансd і Рейнольд ГідеонdНа основі Індіанець в ПарижіdУ головних ролях Тім Аллен[4][2][3], Мартін Шорт[4][2][3], Сем Г...

 

خريف البطريرك (بالإسبانية: El otoño del patriarca)‏    المؤلف غابرييل غارثيا ماركيث  اللغة الإسبانية  تاريخ النشر 1975  النوع الأدبي رواية الديكتاتور،  ورواية  المواقع OCLC 24640222003743  تعديل مصدري - تعديل   خريف البطريرك (بالإسبانية: El otoño del patriarca)‏ هي رواية للروائي الك

2000 single by Limp Bizkit My GenerationSingle by Limp Bizkitfrom the album Chocolate Starfish and the Hot Dog Flavored Water ReleasedSeptember 5, 2000 (2000-09-05)Genre Nu metal[1] rap metal[2] Length3:41LabelFlipInterscopeSongwriter(s)Fred DurstWes BorlandJohn OttoSam RiversProducer(s)Fred DurstDJ LethalLimp Bizkit singles chronology Take a Look Around (2000) My Generation (2000) Rollin (Air Raid Vehicle) (2000) My Generation is a song by the American rap rock...

 

Julieta EstableApodo Tita[1]​País  ArgentinaFecha de nacimiento 15 de julio de 1997 (26 años)Lugar de nacimiento Capital Federal, Buenos AiresAltura 1,69 m (5′ 7″)Entrenador Pancho Mastelli y Leo Squarzon[1]​Brazo hábil Derecho (revés a ambas manos)Perfil oficial WTP Perfil WTPIndividualesRécord de su carrera 176 – 115Títulos de su carrera 0 WTA - 5 ITFRanking actual 755 (5 de septiembre de 2022)Mejor ranking 424 (9 de mayo de 2016)DoblesRécord de su carrera...

 

Lambang bendera Tsesarevich. Lambang Tsesarevich[1] (bahasa Rusia: цесаревич, IPA: [tsɨsɐˈrʲevʲɪtɕ]) merupakan gelar ahli waris tetap atau sementara di Kekaisaran Rusia. Gelar ini mendahului atau menggantikan nama dan patronimik yang diberikan. Tsesarevna Rusia Istri pewaris tsesarevich menyandang gelar Tsesarevna (bahasa Rusia: Цесаревна) – Adipatni Agung. Pada tahun-tahun pertama Kekaisaran Rusia, pewaris perempuan Pyotr I dari Rusia menyandan...

Pulau Kunashir yang dikontrol Rusia (di belakang) dilihat dari Semenanjung Shiretoko Jepang (di depan) Perbatasan Jepang dengan Rusia adalah perbatasan maritim de facto yang memisahkan wilayah perairan kedua negara. Menurut badan perbatasan Rusia, panjang perbatasan ini adalah 194,3 km (120,7 mi).[1] Kedua negara tidak memiliki perbatasan darat, meskipun sebelumnya mereka punya pada periode 1905–1945 ketika pulau Sakhalin terbagi menjadi milik Jepang dan Kekaisaran Rusia (...

 

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (ديسمبر 2018) بطولة أوروبا لكرة الماء 1993 البطولة بطولة أوروبا لكرة الماء رقم الموسم الـ 21 التاريخ 1993 المكان شفيلد، الم...

 

United States historic placeMasonic TempleU.S. National Register of Historic Places Show map of ArizonaShow map of the United StatesLocation212 N. Fourth St.,Kingman, ArizonaCoordinates35°11′24″N 114°3′7″W / 35.19000°N 114.05194°W / 35.19000; -114.05194Built1939Architectural styleModerneMPSKingman MRANRHP reference No.86001164[1]Added to NRHPMay 19, 1986 The Masonic Temple is a historic building located in Kingman, Arizona. The temple...

The Hacker, 2015 The Hacker, mit bürgerlichem Namen Michel Amato, ist ein französischer DJ und Produzent für elektronische Musik. In Kooperation mit Miss Kittin erreichte er mit den Elektropop-Titeln 1982 und Frank Sinatra Ende der 1990er Jahre große Bekanntheit in den deutschen Techno-Clubs. Sein Stil ist durch Kraftwerk, New Wave sowie die französische Rave-Szene Anfang der 1990er Jahre beeinflusst. Inhaltsverzeichnis 1 Biografie 2 Diskografie (Auszug) 2.1 Alben mit Miss Kittin 2.2 Sol...

 

Hubungan Israel–Ukraina Israel Ukraina Isaac Herzog state visit to Ukraine, October 2021 Hubungan Israel–Ukraina adalah hubungan luar negeri antara Israel dan Ukraina. Kedua negara tersebut mengakui satu sama lain secara de facto pada 11 Mei 1949 sebagai RSS Ukraina dan mendirikan hubungan diplomatik de jure pada 26 Desember 1991 sebagai negara independen.[1] Israel memiliki kedubes di Kyiv. Ukraina memiliki kedubes di Tel Aviv dan konjen di Haifa. Referensi ^ From the history of ...

 

Muhammad IISultan GranadaBerkuasa22 Januari 1273 – 8 April 1302PendahuluMuhammad IPenerusMuhammad IIIInformasi pribadiKelahiranca. 1235Kematian8 April (umur 66–67)GranadaWangsaBanu NashriAyahMuhammad IIbuAisyah[1]AnakMuhammad III, Nashr, FathimahAgamaIslam Muhammad II (Arab: محمد الثاني; atau juga dikenali dengan julukannya al-Faqih, yang berarti sang ahli agama, ca. 1235 – 8 April 1302; berkuasa sejak 1273 hingga kematiannya) adalah penguasa Nashri ked...

Pindad Maung Maung varian soft top Jenis Kendaraan utilitas militer ringan Negara asal Indonesia Sejarah pemakaian Masa penggunaan 2021 – sekarang Sejarah produksi Perancang PT MSA dan FAD Works[1] Produsen Pindad Biaya produksi 600 juta rupiah Diproduksi 2020 – sekarang Spesifikasi Berat 2.510 kilogram (5.530 pon) (kosong) Panjang 4.835 mm (190,4 in) Lebar 2.000 mm (78,7 in) Tinggi 1.890 mm (74,4 in) Senjatautama Senapan mesin kal...

 

1955 novel by Cyril M. Kornbluth Gladiator-At-Law First editionAuthorFrederik Pohl and Cyril M. KornbluthCountryUnited StatesLanguageEnglishGenreScience fictionPublisherBallantine BooksPublication dateJune 1955Media typePrint (Paperback)Pages171OCLC13532842 Gladiator-at-Law was serialized in Galaxy Science Fiction in 1954, illustrated by Ed Emshwiller Gladiator-At-Law is a satirical science fiction novel by American writers Frederik Pohl and Cyril M. Kornbluth. It was first published in ...

 

Indian agricultural scientist (born 1958) This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article has an unclear citation style. The references used may be made clearer with a different or consistent style of citation and footnoting. (June 2010) (Learn how and when to remove this template message) This biography of a living person needs additional citations for verification. Please h...

Commuter rail service between Nashville and Lebanon, Tennessee For the American Basketball Association team, see Music City Stars. WeGo StarThree EMD F40PH locomotives in use by the WeGo Star lined up within the Lebanon, Tennessee yards. The third F40PH on the far right is a former Amtrak locomotive painted in its original Pacific Surfliner scheme which has since been repainted as of 2020.OverviewOwnerTennessee Department of Transportation (TDOT)LocaleNashville Metropolitan AreaTransit typeCo...

 

American alternative pop band This article is about the band. For the meal, see Japanese breakfast. Japanese BreakfastJapanese Breakfast frontwoman Michelle Zauner performing at the Day In Day Out Festival in Seattle, Washington, 2022Background informationOriginPhiladelphia, Pennsylvania, U.S.GenresAlternative popindie rockindie popdream popYears active2013–presentLabelsRanchSeagreenYellow KDead OceansPolyvinylW HotelsSony MasterworksMembers Michelle Zauner Peter Bradley Craig Hendrix Deven...

 

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