Bubble sort python - Linux Hint
文章推薦指數: 80 %
Bubble sort. This is the arranging of elements of an array that deals with using the simplest sorting algorithm applied by swapping the adjacent elements ... Sortingistheprocessofarrangingthevaluesinorderpresentintheformoflists.Differenttypesofsortingdiscriminatebecauseoftheirusagetechniquesandapproacheslikequicksort,selectionsort,mergesort,bubblesort,etc.Thistutorialisrelatedtothebubblesort. Bubblesort Thisisthearrangingofelementsofanarraythatdealswithusingthesimplestsortingalgorithmappliedbyswappingtheadjacentelementsrepeatedlyiftheorderiswrong. Bubblesortworking Tosortthevaluesinascendingorder,thenthefirstiterationincludestheprocessofcomparingandswapping.Thefirstindexvalueandthesecondonearecompared.Iftheconditionisfulfilled,swappingoccursandisrepeatedtilltheend. Algorithm/pseudocodeforbubblesort function(array) fori rightvalue swapleftvalueandrightvalue endfunction Example1 Thebubblesortmechanismisappliedtothepythonprogramminglanguagebyusingthefunctionnamedbubblesort.Thesyntaxforthefunctionisthatakeyword‘def’isusedalongwiththefunction’sname.Inthefunctionparameter,wehavepassedanarraythatistobesortedbythefunction.Sonowwewillseethecompletefunctionalityorsaythatthecoreofthewholesortingprocessisdefinedinthefunction’sbody.Firstlywewilldeclarethelengthofthearraytoavariablethroughanassignmentoperatorbyusingthelen()built-infunction. #n=len(arr) Foraccessinganyelementinanarray,wealwaysuseaFORloopinanyprogramminglanguage.Justlikethat,Pythonalsoutilizesthe“for”loopinthesortingprocesstomakeitfeasiblefortheuser.Sothearraywillbetraversedbyusingaforaloop. #ForIinrange(n–1): Here“i”isthevariablerepresentingtheindexnumberinthearrayhavingthearrayofafixedsizeminusone.As‘n’representsthesizeofthearray,so(n-1)representstraversingofthelooptothepositionofthesizeminusonesothatwecaniteratethelooponetimeagainafterasingleiteration. Asdescribedabove,thetwoclosestadjacentindexesarecomparedforthebubblesort.Byusingtheaboveloop,wewillaccessoneindex.Saythefirstone,toaccessthenextindex;wefurtherneedaloop.Thisistheinnerloop,andtheabove-mentionedisdeclaredasanouterloop.Thisphenomenonresemblesthetwo-dimensionalarray(2d).Soletusdeclaretheinnerloop. #forjinrange(0,n-i-1): The‘j’variableislikethe‘i’oftheouterloop,butthiswillrepresentthenextvalueofthecurrentvalueofindex‘i’,aswehaveappliedthelogicof‘n-i-1’,sotheloopwilliteratetillthepositionofsubtractingthevalueof“i”fromthesizeofthearrayalongwith‘-1’value,thiswillleadtotheadjacenttwoindexesinthearray. Wehaveaccessedtwovaluesinthearray,anditistimetocomparethemasweknowthatthecomparisonismadethroughtheangularbrackets.Weneedtousethe‘>’bracketfortheascendingsorting. Ifarr[j]>arr[j+1]: arr[j],arr[j+1]=arr[j+1],arr[j] Ifthevalueattheleftsidethatisaccessedfirstisgreaterthanthevalueontheright,accessedlater,thenboththevaluesareswappeddirectlywithoutusinganyinvolvementofthirdplace.Intheothercase,movetowardsthenextposition.Thiswasthemainlogicfunctionofthebubblesort. Jumpoutsidetheloops.Afterthat,wedeclarethearrayandpassittothefunctionthroughafunctioncall. Bubblesort(arr). Afterthat,thesortedarraywillbeprinted.Intheresultantconsole,theresultantvaluewillbedisplayed. Youcanseethattheinputarraycontainstherandomvalues,whereas,intheresultantarray,alltheelementsaresortedinascendingorder. Example2 Theaboveexampledealswithcontinuingallpossiblecomparisonsevenifthewholearrayisalreadysorted.Thisleadstothetimeextensionoftheexecutionthroughoutthearray.Sotomaketheexecutiontime-limited,wewilluseathirdvariable.HereweuseaBooleanvariabletosetthevariable’svalueastrueifswappingoccurs.Otherwise,itisconsideredfalse. Aftereachiteration,ifnoswappingoccursduetoswapping,thevaluewillbefalse.Itreferstowhenalltheelementsinanarrayarealreadysorted,andthereisnofurtherrequirementtosortthem.Thisphenomenoniseasilyusedandcanreducetheexecutiontimeandbenefitfromoptimizingbubblesort. Insidethebubblesortfunction,thelengthhasbeendeclaredavariable.Anadditionalvariableswappedisdeclaredasfalsebydefaultinitially.Butitsvaluechangeswhenevertheprocessofswappingtakesplace. Swapped=false Insideboththeouterandtheinnerloop,thecomparisonbetweenthevaluesofspecifiedindexesoccurs;ifthevaluesneedtobeexchanged,thentheswappedvariableisturnedinto‘true,’andthevaluesareswappedsuccessfully. Butifnotwovaluesareswapped,whenthevaluesarealreadyarranged,thennoswappingoccurs,sotheswappedvariableremainsfalse.Andthenthebreakoccurs.Thischeckisattainedthroughanif-statement. Ifswapped==false Break Thisbreakwillberesponsibleforstoppingtheloopfromexecutingfurther.Likeinthisexample,thebreakwilloccurattheindexof1,2and3. Aftersavingthefile,theexecutionvaluescanbeseenthroughtheconsole.Youcanseetheresultantvaluesthatarearrangedinascendingorder. Example3 ThisexamplefollowsthesameconceptasexplainedinthesecondexamplebyusingthesameswappedBooleanwiththeuseofanothervariableatthetimeofswappingthevalues.Thisisatempvalue.Thisisatemplatethatstoresthevaluestemporarily. Thesameaboveexampleisusedhere.Onlyconsidertheswappingprocedurehere.Thefirstindexvalueissavedinthevariable‘temp’insidetheloops.Andthatspaceisfilledwiththevaluenexttoitinthearraytowhichthepreviousvalueiscompared.Andthatnextvalueisnowreplacedwiththevaluepresentinthetemp.Thisiscalledindirectassigningofvalues,anditusesmorestepsthanthedirectassignmentofvalues. Theswappedvariablewillbedeclaredastrueintheswappingcase.Executethecodetoseetheresults. Conclusion Thearticle‘bubblesort’containsabriefintroductiontothesortingmethodologythroughthealgorithm.Adetailedprocessofbubblesortwithastep-by-stepapproachisdiscussed.TheSpydertoolisrecommendedfortheimplementationofPython-relatedprograms.EachelementaryexampledepictstheuseofbubblesortinPythonlanguage. Abouttheauthor AqsaYasin Iamaself-motivatedinformationtechnologyprofessionalwithapassionforwriting.IamatechnicalwriterandlovetowriteforallLinuxflavorsandWindows. Viewallposts RELATEDLINUXHINTPOSTS PyTorch–count_nonzero()PyTorch–column_stack()PyTorch–cat()PyTorch–argmin()PerformInverseTrigonometricFunctionsinPyTorchDictionaryComprehensionPythonPyTorch–deg2rad()
延伸文章資訊
- 1Q. Write a program to sort a dictionary's keys using bubble sort ...
Q. Write a program to sort a dictionary's keys using bubble sort and produce the sorted keys ... ...
- 2How to sort dictionary by value in Python? - TutorialsTeacher
We can employ a simple bubble sort to arrange tuples according to the mark component, as shown be...
- 3Python Program for Bubble Sort - GeeksforGeeks
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elem...
- 4bubble sorting in dictionary in python - Stack Overflow
A dictionary has no order: if you add/remove/update elements in a dictionary, the order in which ...
- 512. Write a program to sort a dictionary's values using Bubble ...
Write a program to sort a dictionary's values using Bubble sort and produce the sorted values as ...