Bojer-Mur-Horspolov algoritam

U Informatici, Boyer–Moore–Horspool algoritam or Horspool's algorithm je jedan algoritam za nalaženje podstringova u strings. It was published by Nigel Horspool in 1980.[1]

To je pojednostavljena verzija Bojer–Murovog string search algoritma koji je povezan sa Knuth–Morris–Pratt algoritmom. Algortiam menja prostor ta vreme u cilju dobijanja složenost prosečnog slučaja of O(N) na slučajnom tekstu , iako on ima O(MN) unajgorem slučaju, gde je dužina paterna M , a dužina stringa koji se pretražuje N.

Primer primene

Evo jednog primera implementacije Bojer-Mur-HorspoLovog algoritma, napisan u C.

#include <string.h>
#include <limits.h>

/* Returns a pointer to the first occurrence of "needle"
 * within "haystack", or NULL if not found. Works like
 * memmem().
 */

/* Note: In this example needle is a C string. The ending
 * 0x00 will be cut off, so you could call this example with
 * boyermoore_horspool_memmem(haystack, hlen, "abc", sizeof("abc"))
 */
const unsigned char *
boyermoore_horspool_memmem(const unsigned char* haystack, size_t hlen,
                           const unsigned char* needle,   size_t nlen)
{
    size_t scan = 0;
    size_t bad_char_skip[UCHAR_MAX + 1]; /* Officially called:
                                          * bad character shift */

    /* Sanity checks on the parameters */
    if (nlen <= 0 || !haystack || !needle)
        return NULL;

    /* ---- Preprocess ---- */
    /* Initialize the table to default value */
    /* When a character is encountered that does not occur
     * in the needle, we can safely skip ahead for the whole
     * length of the needle.
     */
    for (scan = 0; scan <= UCHAR_MAX; scan = scan + 1)
        bad_char_skip[scan] = nlen;

    /* C arrays have the first byte at [0], therefore:
     * [nlen - 1] is the last byte of the array. */
    size_t last = nlen - 1;

    /* Then populate it with the analysis of the needle */
    for (scan = 0; scan < last; scan = scan + 1)
        bad_char_skip[needle[scan]] = last - scan;

    /* ---- Do the matching ---- */

    /* Search the haystack, while the needle can still be within it. */
    while (hlen >= nlen)
    {
        /* scan from the end of the needle */
        for (scan = last; haystack[scan] == needle[scan]; scan = scan - 1)
            if (scan == 0) /* If the first byte matches, we've found it. */
                return haystack;

        /* otherwise, we need to skip some bytes and start again.
           Note that here we are getting the skip value based on the last byte
           of needle, no matter where we didn't match. So if needle is: "abcd"
           then we are skipping based on 'd' and that value will be 4, and
           for "abcdd" we again skip on 'd' but the value will be only 1.
           The alternative of pretending that the mismatched character was
           the last character is slower in the normal case (E.g. finding
           "abcd" in "...azcd..." gives 4 by using 'd' but only
           4-2==2 using 'z'. */
        hlen     -= bad_char_skip[haystack[last]];
        haystack += bad_char_skip[haystack[last]];
    }

    return NULL;
}

Karakteristike

Algoritam se najbolje pokazuje sa dugačkim stringovima, kada dosledno pogađa karakter koji se ne podudara na ili blizu kraja psolednjeg bajta trenutne poyicije u plastu sena i psolednjeg bajta igle koji se više ne ponavljaju u celoj igli. Na primer 32 bajta needle se zavrsava sa "z" pretražuje kroz 255 bajtova sena slame koji nema 'z' bajt , za to će biti potrebno 224 ponavljanja.

Najbolji slučaj je isti kao za Boyer–Moore string search algoritam iuveliko O notaciji, iako konstantno iznad inicijalizacije i za svaku petlju je manje.

Ponašanje u najgorem slucaju se dešava kada je loš karakter koji prskačete konstantno nizak (sa donje granice od 1 bajta kretanja) i kada veliki deo igel odgovara plastu sena. Loš karakter preskačete samona parcijalnom pokdudaranju, kada se konačni karakter igle pojavljuje i u ostalim delovima igle, sa jednim bajtom kretanja dešava se kada je isti bajtu obe poslednje dve pozicije.

kanonski degenerisan slučaj sličan gornjem najboljem slučaju je igla za 'a' bajt praćena sa 31 'z' bajtova u plastu sena koji se sastoji od 255 'z' bajtova. Ovo ce uraditi 31 uspešno bajt poređenje, 1 bajt poređenje koje ne uspe, a zatim krenuti napred 1 bajt. Ovaj proces će se ponoviti223 puta (255 - 32), svodeći totalno poredjenje bajtova na 7,168 (32 * 224).

Najgori slučaj je znatno veći nego za Boyer–Moore string search algoritam, iako je jasno da je teško postići unormalnim slučajevima korišćenja. takođe je vredno napomenuti da je ovaj najgori slučaj, najgori slučaj i za naivne (but usual) memmem() algoritme, iako implementacija ima tendenciju da bude ynatno optimizovanan (i više je keš prijateljski).

Vidi još

Reference

  1. ^ R. N. Horspool (1980). „Practical fast searching in strings”. Software - Practice & Experience. 10 (6): 501—506. doi:10.1002/spe.4380100608. [Претплата неопходна (помоћ)]. 

Spoljašnje veze

Read other articles:

В Википедии есть статьи о других людях с такой фамилией, см. Мартынюк. Николай Каленикович Мартынюк командующий 73-й воздушной армией 1978 — 1984 Рождение 17 декабря 1928(1928-12-17)Киев, СССР Смерть 6 сентября 2015(2015-09-06) (86 лет) Партия КПСС Награды Николай Каленикович Мартынюк — с�...

Тренеррос. Тренер Жанр спортивнийРежисер Яків БазелянСценарист Олександр ЛапшинУ головних ролях Валерій РижаковОператор Валерій БазильовКомпозитор Олексій МуравльовХудожник Борис КомяковКінокомпанія Кіностудія ім. М. ГорькогоТривалість 84 хв.Мова російськаКраїна &#...

Sansculottides (pengucapan bahasa Prancis: [sɑ̃kylɔtid]; juga Epagomènes; Prancis: Sans-culottides, Sanculottides, jours complémentaires, jours épagomènes) adalah hari raya setelah bulan terakhir dari tahun pada Kalender Revolusi Prancis yang dipakai setelah Revolusi Prancis dari sekitar 1793 sampai 1805. Sansculottides, yang mengambil nama dari Sansculottes, menyusul dua belas bulan 30 hari dari Kalender Republik tersebut dengan lima hari dasar pada tahun umum atau enam hari komp...

Pour les articles homonymes, voir 116e régiment. Cet article est une ébauche concernant une unité ou formation militaire française. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. 116e régiment d'infanterie Insigne régimentaire du 116e Régiment d’Infanterie Pays France Branche Armée de terre Type régiment d'infanterie Rôle infanterie Inscriptionssur l’emblème Tudela 1808Saragosse 1809Lérida 1...

Leader of South Africa from 1989 to 1994 In this article, the surname is de Klerk, not Klerk. His ExcellencyF. W. de KlerkOMG DMSde Klerk in 19907th State President of South AfricaIn office14 August 1989 – 10 May 1994Preceded byP. W. BothaSucceeded byNelson Mandela (as President)1st Deputy President of South AfricaIn office10 May 1994 – 30 June 1996Serving with Thabo MbekiPresidentNelson MandelaPreceded byAlwyn Schlebusch (as Vice State President)Succ...

Weihe von Bischof André-Maurice Bovet, Bischof von Lausanne und Genf André-Maurice Bovet (* 29. November 1865 in Autigny, Kanton Freiburg; † 3. August 1915 in Freiburg) war ein Schweizer römisch-katholischer Geistlicher und Bischof von Lausanne und Genf. Inhaltsverzeichnis 1 Leben 2 Wirken 3 Literatur 4 Weblinks Leben André-Maurice Bovet war der Sohn des Landwirts Joseph Bovet und dessen Ehefrau Françoise geb. Dafflon. Er besuchte von 1879 bis 1887 das Kollegium St. Michael in Freiburg...

American racing driver (born 1962) Michael AndrettiAndretti in 2007BornMichael Mario Andretti (1962-10-05) October 5, 1962 (age 61)Bethlehem, Pennsylvania, U.S.Championship titlesCART Championship Car (1991) Major victories Long Beach Grand Prix (1986, 2002) Michigan 500 (1987, 1989)Champ Car career309 races run over 19 yearsBest finish1st (1991)First race1983 Caesars Palace Grand Prix (Caesars Palace)Last race2002 Gran Premio Telmex-Gigante (Mexico City)First win1986 Long Beach Grand Pr...

Jamal Crawford merupakan pemimpin NBA karier empat poin permainan. Dalam permainan bola basket, sebuah four-point play atau empat poin permainan merupakan kejadian yang jarang, ketika seorang pemain penyerang menembak dan membuat suatu angka tiga poin permainan sementara sekaligus di langgar oleh seorang pemain bertahan, menghasilkan suatu tembakan pelanggaran (shooting foul) dan 1 usaha lemparan bebas atau 2 poin permainan dan dengan sengaja atau pelanggaran keras saat menembak dan di hadiah...

Regional unit in Central Greece, GreeceEvrytania Περιφερειακή ενότηταΕυρυτανίαςRegional unitMunicipalities of EvrytaniaEvrytania within GreeceCoordinates: 39°0′N 21°40′E / 39.000°N 21.667°E / 39.000; 21.667CountryGreeceRegionCentral GreeceCapitalKarpenisiArea • Total1,868 km2 (721 sq mi)Population (2011) • Total20,081 • Density11/km2 (28/sq mi)Time zoneUTC+2 • ...

Indarasakdi SachiอินทรศักดิศจีPutri permaisuri SiamPeriode(1) 10 Juni 1921 – 1 Januari 1922 (2) 15 September 1925 – 30 November 1975Ratu permaisuri SiamPeriode1 January 1922 – 15 September 1925Informasi pribadiKelahiran(1902-06-10)10 Juni 1902Bangkok, SiamKematian30 November 1975(1975-11-30) (umur 73)Bangkok, ThailandWangsaDinasti ChakriNama lengkapbahasa Inggris: Indrasakdi Sachi bahasa Thai: อินทรศักดิศจีAyahPluem Suchar...

Terror Tales was the name of two American publications: a pulp magazine of the weird menace genre of the 1930s, and a horror comic in the 1960s and 1970s. Pulp magazine Terror Tales was originally published by Popular Publications. The first issue was published in September 1934[1] One of the most successful horror magazines, it was joined shortly afterwards (1935) with its sister horror pulp, Horror Stories, also from the same publisher. Some of the writers whose work appeared in Ter...

Hymn composed by Ravana in the praise of Shiva You can help expand this article with text translated from the corresponding article in Hindi. (August 2023) Click [show] for important translation instructions. View a machine-translated version of the Hindi article. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting mac...

This article is about David Lennox, a bridge builder. For the American inventor, see Dave Lennox. Not to be confused with David Thomas Lenox. David LennoxBornAyr, ScotlandBaptisedFebruary 1788Died12 November 1873(1873-11-12) (aged 85)New South WalesNationalityBritishKnown forPioneering bridge building Lansdowne Bridge over Prospect Creek on the Hume Highway at Lansdowne. Opened in 1836, it carries traffic to this day. David Lennox (1788 – 12 November 1873) was a Scottish-Australia...

Motions induced on bodies within a fluid flow due to vortices in the fluid Numerical simulation of vortex-induced vibrations due to the flow around a circular cylinder.[1] In fluid dynamics, vortex-induced vibrations (VIV) are motions induced on bodies interacting with an external fluid flow, produced by, or the motion producing, periodic irregularities on this flow. A classic example is the VIV of an underwater cylinder. How this happens can be seen by putting a cylinder into the wat...

Questa voce sull'argomento calciatori albanesi è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. Emiliano Çela Nazionalità  Albania Altezza 182 cm Peso 73 kg Calcio Ruolo Allenatore (ex Difensore) Termine carriera 2021 - giocatore Carriera Squadre di club1 2003-2006 Partizani Tirana? (?)2006-2007 Shkumbini? (?)2007-2008 Laçi? (?)2008-2009 Lushnja14 (0)2009-2010 Laçi30 (0)...

Daewoo Lanos Модель первых лет выпуска в кузове седан Общие данные Производитель Daewoo Годы производства 1996—2020 Сборка ТагАЗ (Таганрог, Россия) АгромашХолдинг (Костанай, Казахстан) FSO (Варшава, Польша) ЗАЗ (Запорожье, Украина) GM Egypt[en] (Каир, Египет) Daewoo Motors Egypt (Город имени 6 октября, Е...

Chilean-American singer In this Spanish name, the first or paternal surname is Castillo and the second or maternal family name is Astorga. Paloma MamiBackground informationBirth namePaloma Rocío Castillo AstorgaBorn (1999-11-11) November 11, 1999 (age 24)Manhattan, New York, U.S.[1]GenresReggaetonLatin R&BLatin trapOccupation(s)SingerInstrument(s)VocalsYears active2018-presentLabelsSony Latin[2]Websitepalomamamimusic.comMusical artist Paloma Rocío Castillo A...

Test given to Latin students This article relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: National Latin Exam – news · newspapers · books · scholar · JSTOR (November 2022) (Learn how and when to remove this template message) National Latin Exam silver medal The National Latin Exam is a test given to Latin students. Sponsored by the U.S.-based American Classical Leag...

Si ce bandeau n'est plus pertinent, retirez-le. Cliquez ici pour en savoir plus. Cet article est orphelin. Moins de trois articles lui sont liés (mai 2021). Vous pouvez aider en ajoutant des liens vers [[Problème de la fourmi sur un élastique]] dans les articles relatifs au sujet. Le problème de la fourmi sur un élastique est un puzzle mathématique dont la solution semble paradoxale ou du moins contre-intuitive. Les détails du puzzle peuvent varier, la fourmi est parfois remplacée par...

Wrestlingat the Games of the XXVI OlympiadVenueGeorgia World Congress CenterDates20 July – 2 August 1996No. of events20Competitors401 from 75 nations← 19922000 → Wrestling at the1996 Summer OlympicsFreestyleGreco-Roman48 kg48 kg52 kg52 kg57 kg57 kg62 kg62 kg68 kg68 kg74 kg74 kg82 kg82 kg90 kg90 kg100 kg100 kg130 kg130 kgvte At the 1996 Summer Olympics, two different wrestling disciplines were contested: freestyle wrestling and Greco-Roman wrestling.[1]...