Share to: share facebook share twitter share wa share telegram print page

In-place algorithm

In computer science, an in-place algorithm is an algorithm that operates directly on the input data structure without requiring extra space proportional to the input size. In other words, it modifies the input in place, without creating a separate copy of the data structure. An algorithm which is not in-place is sometimes called not-in-place or out-of-place.

In-place can have slightly different meanings. In its strictest form, the algorithm can only have a constant amount of extra space, counting everything including function calls and pointers. However, this form is very limited as simply having an index to a length n array requires O(log n) bits. More broadly, in-place means that the algorithm does not use extra space for manipulating the input but may require a small though nonconstant extra space for its operation. Usually, this space is O(log n), though sometimes anything in o(n) is allowed. Note that space complexity also has varied choices in whether or not to count the index lengths as part of the space used. Often, the space complexity is given in terms of the number of indices or pointers needed, ignoring their length. In this article, we refer to total space complexity (DSPACE), counting pointer lengths. Therefore, the space requirements here have an extra log n factor compared to an analysis that ignores the length of indices and pointers.

An algorithm may or may not count the output as part of its space usage. Since in-place algorithms usually overwrite their input with output, no additional space is needed. When writing the output to write-only memory or a stream, it may be more appropriate to only consider the working space of the algorithm. In theoretical applications such as log-space reductions, it is more typical to always ignore output space (in these cases it is more essential that the output is write-only).

Examples

Given an array a of n items, suppose we want an array that holds the same elements in reversed order and to dispose of the original. One seemingly simple way to do this is to create a new array of equal size, fill it with copies from a in the appropriate order and then delete a.

 function reverse(a[0..n - 1])
     allocate b[0..n - 1]
     for i from 0 to n - 1
         b[n − 1 − i] := a[i]
     return b

Unfortunately, this requires O(n) extra space for having the arrays a and b available simultaneously. Also, allocation and deallocation are often slow operations. Since we no longer need a, we can instead overwrite it with its own reversal using this in-place algorithm which will only need constant number (2) of integers for the auxiliary variables i and tmp, no matter how large the array is.

 function reverse_in_place(a[0..n-1])
     for i from 0 to floor((n-2)/2)
         tmp := a[i]
         a[i] := a[n − 1 − i]
         a[n − 1 − i] := tmp

As another example, many sorting algorithms rearrange arrays into sorted order in-place, including: bubble sort, comb sort, selection sort, insertion sort, heapsort, and Shell sort. These algorithms require only a few pointers, so their space complexity is O(log n).[1]

Quicksort operates in-place on the data to be sorted. However, quicksort requires O(log n) stack space pointers to keep track of the subarrays in its divide and conquer strategy. Consequently, quicksort needs O(log2 n) additional space. Although this non-constant space technically takes quicksort out of the in-place category, quicksort and other algorithms needing only O(log n) additional pointers are usually considered in-place algorithms.

Most selection algorithms are also in-place, although some considerably rearrange the input array in the process of finding the final, constant-sized result.

Some text manipulation algorithms such as trim and reverse may be done in-place.

In computational complexity

In computational complexity theory, the strict definition of in-place algorithms includes all algorithms with O(1) space complexity, the class DSPACE(1). This class is very limited; it equals the regular languages.[2] In fact, it does not even include any of the examples listed above.

Algorithms are usually considered in L, the class of problems requiring O(log n) additional space, to be in-place. This class is more in line with the practical definition, as it allows numbers of size n as pointers or indices. This expanded definition still excludes quicksort, however, because of its recursive calls.

Identifying the in-place algorithms with L has some interesting implications; for example, it means that there is a (rather complex) in-place algorithm to determine whether a path exists between two nodes in an undirected graph,[3] a problem that requires O(n) extra space using typical algorithms such as depth-first search (a visited bit for each node). This in turn yields in-place algorithms for problems such as determining if a graph is bipartite or testing whether two graphs have the same number of connected components.

Role of randomness

In many cases, the space requirements of an algorithm can be drastically cut by using a randomized algorithm. For example, if one wishes to know if two vertices in a graph of n vertices are in the same connected component of the graph, there is no known simple, deterministic, in-place algorithm to determine this. However, if we simply start at one vertex and perform a random walk of about 20n3 steps, the chance that we will stumble across the other vertex provided that it is in the same component is very high. Similarly, there are simple randomized in-place algorithms for primality testing such as the Miller–Rabin primality test, and there are also simple in-place randomized factoring algorithms such as Pollard's rho algorithm.

In functional programming

Functional programming languages often discourage or do not support explicit in-place algorithms that overwrite data, since this is a type of side effect; instead, they only allow new data to be constructed. However, good functional language compilers will often recognize when an object very similar to an existing one is created and then the old one is thrown away, and will optimize this into a simple mutation "under the hood".

Note that it is possible in principle to carefully construct in-place algorithms that do not modify data (unless the data is no longer being used), but this is rarely done in practice.

See also

References

  1. ^ The bit space requirement of a pointer is O(log n), but pointer size can be considered a constant in most sorting applications.
  2. ^ Maciej Liśkiewicz and Rüdiger Reischuk. The Complexity World below Logarithmic Space. Structure in Complexity Theory Conference, pp. 64–78. 1994. Online: p. 3, Theorem 2.
  3. ^ Reingold, Omer (2008), "Undirected connectivity in log-space", Journal of the ACM, 55 (4): 1–24, doi:10.1145/1391289.1391291, MR 2445014, S2CID 207168478, ECCC TR04-094

Read other articles:

Wilayah biogeografis Indo-Pasifik, ditunjukkan oleh warna biru tua Indo-Pasifik, dalam literatur lain juga disebut Indo-Pasifik Barat, adalah salah satu wilayah biogeografis bahari di dunia. Kawasan ini meliputi perairan bahari tropika di Samudra Hindia, Samudera Pasifik bagian barat dan tengah, serta laut-laut pedalaman di wilayah Indonesia dan Filipina. Wilayah ini tidak termasuk perairan ugahari dan kutub di samudera-samudera Hindia dan Pasifik. Demikian pula, perairan tropis di Pasifik timur…

Balika VadhuNama alternatifBalika Vadhu – Kacchi Umar Ke Pakke RishteBalika Vadhu – Lamhe Pyaar KeGenreDramaDitulis olehPurnendu ShekharGajra Kottary[1]Rajesh DubeyEmraanUsha DixitRaghuvir TomagolaManisha SinghKovid GuptaRaman ManaktalaSutradaraSidharth SenguptaPradeep YadavPengarah kreatifSiddhartha VankarLagu pembukaLagu Chhoti si UmarNegara asalIndiaBahasa asliHindiJmlh. musim2Jmlh. episode2.248ProduksiProduser eksekutifZakir ShaikhSachin ChavanFuzel KhanProduserSunjoy WaddhwaComa…

Segunda División B Venezolana 2009-10 Datos generalesSede VenezuelaFecha 6 de septiembre de 2009PalmarésPrimero Lotería del TáchiraSegundo Minasoro FCDatos estadísticosParticipantes 17 Cronología Segunda División B Venezolana 2008-09 Segunda División B Venezolana 2009-10 Segunda División B Venezolana 2010-11 [editar datos en Wikidata] La Temporada 2009/010 del Fútbol profesional Venezolano de la Segunda División B de Venezuela se inició el 6 de septiembre de 2009 con la par…

1970 Massachusetts general election ← 1968 November 3, 1970 1972 → Part of the1970 United States elections Elections in Massachusetts General 1942 1944 1946 1948 1950 1952 1954 1956 1958 1960 1962 1964 1966 1970 1974 1978 1982 1986 1990 1994 1998 2002 2006 2008 2010 2012 2014 2016 2018 2020 2022 Federal government U.S. President 1788–89 1792 1796 1800 1804 1808 1812 1816 1820 1824 1828 1832 1836 1840 1844 1848 1852 1856 1860 1864 1868 1872 1876 1880 1884 1888 1892 1896 19…

Ateliers Schaudel Rechtsform Gründung Mitte der 1890er Jahre Auflösung 1902 Sitz Bordeaux, Frankreich Leitung Charles Schaudel Branche Automobile Schaudel von 1901 Ateliers Schaudel war ein französischer Hersteller von Automobilen und Fahrrädern.[1][2][3] Inhaltsverzeichnis 1 Unternehmensgeschichte 2 Fahrzeuge 3 Literatur 4 Weblinks 5 Einzelnachweise Unternehmensgeschichte Charles Schaudel gründete das Unternehmen Mitte der 1890er Jahre in Bordeaux zur Fahrradprodukt…

أغلى من عينيه البلد مصر  اللغة الأصلية اللهجة المصرية  الطاقم المخرج عز الدين ذو الفقار  سيناريو عز الدين ذو الفقار  موسيقى محمد حسن الشجاعي  تعديل مصدري - تعديل   فيلم أغلى من عينيه هو فيلم درامي ورومانسي إنتاج 1955 من كتابة وسيناريو وإخراج عزالدين ذوالفقار. الف

راؤول ولنبرغ Raoul Wallenberg معلومات شخصية اسم الولادة (بالسويدية: Raoul Gustaf Wallenberg)‏  الميلاد 4 أغسطس 1912(1912-08-04)ستوكهولم، السويد الوفاة 17 يوليو 1947 (34 سنة)موسكو، الاتحاد السوفيتي مكان الاعتقال سجن ليفورتوفومبنى لوبيانكا  مواطنة السويد  الحياة العملية المدرسة الأم جامعة ميشيغان…

Командувач 7-го фронту генерал Дойхара Кенджі в Сингапурі (1944). Капітуляція 7-го фронту: генерал Ітаґакі Сейшіро віддає свій меч генералові Мессерві. 7-й фро́нт (яп. 【第七方面軍】) — вище оперативно-стратегічне об'єднання збройних сил Японської імперії, фронт Імперської армі…

Небесні сфери з рукопису Коперника Геліоцентрична система Геліоцентризм (нижня панель) у порівнянні з геоцентричною моделлю (верхня панель) Геліоцентри́зм або Геліоцентри́чна систе́ма сві́ту (від грец. ηλιος «сонце» і лат. centrum «осереддя, центр») — вчення в астрономії

أسيوط لتكرير البترولأسيوط لتكرير البترولمعلومات عامةالجنسية مصر التأسيس 1984النوع قطاع عامالمقر الرئيسي جحدم، منفلوط، أسيوط، جمهورية مصر العربيةموقع الويب asorc.com المنظومة الاقتصاديةالشركة الأم الهيئة المصرية العامة للبترولالصناعة تكرير البترولمناطق الخدمة محافظات جمهور…

Kriegerdenkmal in Posen Das Kriegerdenkmal war ein Denkmal in Posen. Es wurde 1870 zur Erinnerung an die Gefallenen der Schlacht bei Nachod von 1866 eingeweiht und 1919 wieder abgerissen. Inhaltsverzeichnis 1 Geschichte 2 Denkmal 3 Literatur 4 Weblinks Geschichte Die Schlacht bei Nachod am 27. Juni 1866 war die erste größere militärische Auseinandersetzung des Preußisch-Österreichischen Krieges, sie endete mit einem preußischen Sieg. 1868 wurde durch Generäle des V. Armee-Corps beschlosse…

Japanese freestyle skier Kenro ShimoyamaPersonal informationNationalityJapaneseBorn (1982-03-12) 12 March 1982 (age 41)Yuzawa, JapanSportSportFreestyle skiing Kenro Shimoyama (下山 研郎, Shimoyama Kenrō, born 12 March 1982) is a Japanese freestyle skier. He competed in the men's moguls event at the 2002 Winter Olympics.[1] References ^ Kenro Shimoyama. Olympedia. Retrieved 9 July 2020. This biographical article relating to freestyle skiing in Japan is a stub. You can help Wikip…

Swedish footballer (born 1994) Victor Lindelöf Lindelöf playing for Sweden in 2019Personal informationFull name Victor Jörgen Nilsson Lindelöf[1]Date of birth (1994-07-17) 17 July 1994 (age 29)[2]Place of birth Västerås, SwedenHeight 1.87 m (6 ft 2 in)[3]Position(s) DefenderTeam informationCurrent team Manchester UnitedNumber 2Youth career IK Franke Västerås IK2007–2009 Västerås SK2012–2013 BenficaSenior career*Years Team Apps (Gls)2009…

В Википедии есть статьи о других людях с фамилией Бельских. Иосиф Михайлович Бельских Дата рождения 4 апреля 1919(1919-04-04) Место рождения с. Арамашево, Верхотурский уезд, Пермская губерния, Российская империя Дата смерти 7 декабря 1987(1987-12-07) (68 лет) Место смерти Алапаевск, Св…

Peta Kabupaten Wajo di Sulawesi Selatan Berikut adalah daftar kecamatan dan kelurahan di Kabupaten Wajo, Provinsi Sulawesi Selatan, Indonesia. Kabupaten Wajo terdiri dari 14 kecamatan, 48 kelurahan dan 142 desa. Pada tahun 2017, kabupaten ini memiliki luas wilayah 2.504,06 km² dan jumlah penduduk sebesar 460.719 jiwa dengan sebaran penduduk 184 jiwa/km².[1][2] Daftar kecamatan dan kelurahan di Kabupaten Wajo, adalah sebagai berikut: Kode Kemendagri Kecamatan Jumlah Kelurahan Ju…

Polícia de Vigilância e Defesa do Estado Organização Natureza jurídica Serviço público Atribuições Polícia de estrangeiros, fronteiras e segurança do Estado Dependência Governo da República Portuguesa Ministério do Interior Documento institucional Decreto-Lei n.º 22 992, de 29 de agosto de 1933 Localização Jurisdição territorial Portugal Continental Sede Rua António Maria Cardoso, Lisboa Histórico Antecessores Polícia de Defesa Política e SocialPolícia Internacional Portu…

Tavern in New York City 40°44′09″N 74°00′21″W / 40.73583°N 74.00583°W / 40.73583; -74.00583 The White Horse Tavern in 1961 The interior in January 2007 The White Horse Tavern, located in New York City's borough of Manhattan at Hudson Street and 11th Street, is known[by whom?] for its 1950s and 1960s bohemian culture. It is one of the few major gathering-places for writers and artists from this period in Greenwich Village (specifically the West Village)…

American actor and filmmaker (born 1979) John KrasinskiKrasinski during an interview in April 2018BornJohn Burke Krasinski (1979-10-20) October 20, 1979 (age 44)Boston, Massachusetts, U.S.Alma materBrown University (BA)OccupationsActorfilm directorfilm producerscreenwriterYears active2000–presentWorksFilmographySpouse Emily Blunt ​(m. 2010)​Children2AwardsFull list John Burke Krasinski (/krəˈzɪnski/[1] born October 20, 1979)[2] is …

American politician Kam BucknerMember of the Illinois House of Representativesfrom the 26th districtIncumbentAssumed office January 18, 2019Preceded byChristian Mitchell Personal detailsBornKambium Elijah Buckner (1985-05-12) May 12, 1985 (age 38)Chicago, Illinois, U.S.Political partyDemocraticEducationUniversity of Illinois, Urbana-Champaign (BA)DePaul University (JD)SignatureCollege football careerNo. 59PositionOffensive tackleDefensive lineClass2007Personal informati…

2009 video game 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 relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: Zuma's Revenge! – news · newspapers · books · scholar · JSTOR (November 2011) (Learn how and when to remove this template message) This arti…

Kembali kehalaman sebelumnya

Lokasi Pengunjung: 18.191.218.194