An warware: quicksort

Quicksort yana ษ—aya daga cikin ingantattun algorithms rarrabuwa, yana alfahari da matsakaicin matsakaicin lokaci na O(n log n). Dangane da tsarin raba-da-ci, yana baje kolin ayyuka masu ban sha'awa yayin rarrabuwar manyan bayanan bayanai. Masanin kimiyyar kwamfuta na Burtaniya Tony Hoare ne ya ฦ™irฦ™ira a cikin 1959 kuma aka buga shi a 1961, quicksort ya zama babban ษ“angaren kimiyyar kwamfuta da shirye-shirye..

Quicksort's shahararsa kuma saboda sauฦ™in aiwatarwa a cikin harsunan shirye-shirye daban-daban. A cikin wannan labarin, za mu bincika yadda za a iya aiwatar da sauri ta hanyar amfani da yaren shirye-shiryen Haskell, harshen shirye-shiryen da aka rubuta a kididdigar da aka sani da tsafta, taฦ™aitacciya, da ฦ™ayatarwa.

Ta yaya Quicksort ke aiki?

Quicksort yana aiki ta zaษ“ar 'pivot' daga saitin bayanai da kuma rarraba sauran abubuwa zuwa rukuni biyu - waษ—anda ba su kai pivot ba da waษ—anda suka fi pivot girma. Wannan mataki, wanda aka sani da 'bangare', ana aiwatar da shi akai-akai har sai an jera jeri.

quicksort :: Ord a => [a] -> [a]
quicksort [] = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
    where
        lesser  = filter (<  p) xs
        greater = filter (>= p) xs

Lambar Haskell da ke sama tana farawa ta hanyar ayyana harka ta tushe don jerin fanko, wanda ke dawo da lissafin fanko. Don lissafin da ba fanko ba, yana zaษ“ar pivot (a cikin wannan yanayin, kashi na farko na jerin), sannan ta tace sauran jerin zuwa jerin abubuwa biyu - ษ—aya tare da abubuwan ฦ™asa da pivot, ษ—ayan kuma tare da abubuwan da suka fi ko girma. daidai da pivot.

Fahimtar aiwatar da Haskell

A cikin aiwatar da Haskell ษ—in mu, muna yin amfani da ฦ™arfin fahimtar lissafin harshe da ayyuka masu girma.

Layin lambar `(ฦ™ananan sauri) ++ [p] ++ (mai sauri mafi girma)` a taฦ™aice yana ษ—aukar ainihin ma'anar quicksort - yana sake tsarawa duka 'ฦ™ananan' da 'mafi girma' jerin sunayen 'ฦ™ananan' da 'mafi girma', sa'an nan kuma ya haษ—a waษ—annan abubuwan da aka jera tare da pivot. a tsakiya. Wannan ita ce dabarar raba da cin nasara a aikace.

Duk da sauฦ™in sa, wannan aiwatarwa na iya zama mara inganci don manyan jeri, yayin da yake tace kowane jerin sunayen sau biyu. Duk da haka, yana aiki azaman babban mafari don fahimtar yadda quicksort ke aiki a Haskell.

Haskell Programming and Quicksort

Kyawawan ladabi da sauฦ™i na quicksort a cikin Haskell suna ฦ™arfafa ฦ™arfin shirye-shiryen aiki. Takaitaccen lambar kuma yana nuna ฦ™arfin jerin ayyukan Haskell.

Buga a tsaye na Haskell yana hana yawancin yuwuwar kwari a lokacin tattara-lokaci, yayin da tsarkinta (babu sakamako mai lahani) da ฦ™arancin ฦ™ima (ba a aiwatar da lissafin sai an buฦ™ata) yana sauฦ™aฦ™e tunani game da haษ“aka lambar.

Daga qarshe, quicksort ba kawai ingantaccen rarrabuwar algorithm bane amma shaida ne ga ฦ™arfin shirye-shiryen aiki da ฦ™arfin Haskell a matsayin harshe.

Shafi posts:

Leave a Comment