Escolar Documentos
Profissional Documentos
Cultura Documentos
http://www.ccs.neu.edu/jpt/archive/2.6.0/applets/PlayingCards/applet.htm
AdamMeyers,NYU June,2008
MUSICOMPUTATION SortingAlgorithms June,2008
Outline
WhatisanAlgorithm? WhatisSorting? WhatisaSortingAlgorithm? SomeSortingAlgorithms AsymptoticComplexity Summary
MUSICOMPUTATION SortingAlgorithms June,2008
WhatisanAlgorithm?
Arecipeforsolvingaproblem Algorithmscanbeimplemented
Bydifferentprograms Indifferentprogramminglanguages
Differentalgorithmsforsolvingthesameproblem
Aremoreefficientiftheyrequirefewerbasicoperations Maysolvedifferentinstancesofthesameproblemmore orlessefficiently
MUSICOMPUTATION SortingAlgorithms June,2008
WhatisSorting?
Sorting=CreateasequenceofitemsinaSetS
Suchthatabinaryrelation(e.q.,)holdsforpairsof consecutiveelements
WeassumeCARD1<CARD2iff
FaceValue(CARD1)<FaceValue(CARD2)
2<3<4<...<J<Q<K<A
FaceValue(CARD1)=FaceValue(CARD2)AND SuitValue(CARD1)<SuitValue(CARD2)
CLUBS<DIAMONDS<HEARTS<SPADES
MUSICOMPUTATION SortingAlgorithms June,2008
WhatisaSortingAlgorithm?
Analgorithmforsortingasetofelements Differentalgorithmsmaybebetter(more efficient)forsortingunderdifferent circumstances
InsertionSort
Startwithashuffleddeckofcards
Deck=Card1,Card2,...Card52
ChooseaspottostoreyourResult
Result=asequenceof0ormorecards Resultisinitiallyempty
ForeachCardNfromCard1toCard52
Followtheinstructionsonthenextslide
InsertionSort:ForeachCardN
IfthecardsrunoutbeforeplacingCardN
InsertCardNatthefrontofResult
BubbleSort
DoBubbleuntilthecardsaresorted,i.e.,untilthe stepsdonotresultinanyswappingofcards. Bubble:ForeachCardNbetweenCard1..51
IfCARDN>CARDN+1,swaptheorderofthetwocards (CARDNbecomesCARDN+1)
MergeSort
Ifthedeckhasonlyonecard
Thereisnothingtodo
Otherwise
Dividethedeckofcardsinhalf MergeSorteachhalf Mergeeachhalftogether
Mergeisdefinedonthenextslide
MUSICOMPUTATION SortingAlgorithms June,2008
Merge(forusebyMergeSort)
Inputconsistsof2SortedPilesofCards:
Pile1andPile2
BeginwithanemptyResultanddothe followinguntiloneorbothpilesareempty
ComparethetopcardsofPile1andPile2and placethelowestcardfacedowninResult
IfoneofthetwoPilesisnonempty,placethe nonemptypileattheendoftheResult
MUSICOMPUTATION SortingAlgorithms June,2008
MergeSort:NumberofComparisons
Foranysetofnthings,youcandividethosen thingsinhalflog2ntimesbeforeyouendupwith just1thingineachhalf(approximately) Eachsplitcorrespondstomergesinvolving51 comparisons(seeMergeinthepreviousslide) Thereareapproximately51Xlog252291 comparisons
MUSICOMPUTATION SortingAlgorithms June,2008
QuickSort
QuickSortLEFTandRIGHT Formasinglestack
LEFTontopofPIVOTontopofRIGHT
MUSICOMPUTATION SortingAlgorithms June,2008
QuickSort2
QuickSortinvolvesintheballparkof52 log252=296comparisonsonaverage QuickSortinvolves52X52=2704 comparisonsintheworstcase. Typicallyittendstohavefewercomparions thanMergeSort(andotheralgorithms)and isthusassumedtobequicker
RadixSort
Combinethestacks:
firstontopofsecondontopofthirdontopoffourth
NextSlide
Gothroughall52cardsand
RadixSort2
Combinethestacks:
firstontopofsecondontopofthird,...,12thontopof13th
I.e.,sorttheleastsignificantdigitorequivalentfirst
MUSICOMPUTATION SortingAlgorithms June,2008
Algorithmsarejudgedby
Complexity
Time(howfast) Space(howmuchmemory)
Asymptoticcomplexity
Asdatasizeincreases,howfastdoestime/spaceuse increase
UpperBoundcomplexity(BigO)
Worsecase
Othercases:
LowerBound Average
MUSICOMPUTATION SortingAlgorithms June,2008
AsymptoticTimeComplexity
Countnumberofbasicoperations
Comparisonsoftwocards Insertionsofcards
Evaluatingsortingalgorithms
Asthesizeofthedeckofcardsincreases,
Howmanymorecomparisonsandinsertionsarethere?
ComplexityisApproximate
Whenyouweighanelephant,doyouconsiderthe weightofaflyonitsback? Complexity
Expressedasapolynominal BigOnotationtakeshighestterm,ignoringconstants 4X3+X23becomesO(X3)
FiguringoutComplexity
InMergeSort(supposen=52)
yousplitthedecklog2ntimes
Fora52carddeck,youhavetodoabout6splitsbefore youhavejust1cardinapile
Thenforeachsplitofthewholedeck,youmustdo n1comparisons(let'sroundoffton)
i.e.thereare51comparisonsfora52carddeck
ncomparisonsXlog2nsplitsmeansthat... MergeSorthasannlog2ntimecomplexity
Approximately300comparisonsfor52cards
MUSICOMPUTATION SortingAlgorithms June,2008
PatternofGrowth
n 1 2 3 4 5 6 logn 0 1 1.6 2 2.3 2.6 2n 2 4 6 8 10 12 nlogn 0 2 4.8 8 11.6 15.5 N2 1 4 9 16 25 36 2n 2 4 8 16 32 64
GraphingComplexities
AsymptoticComplexityisanEstimate
ActualComlexity Asymptotic1 Asymptotic2 3n7000 3n exponential n3+n22 n3 cubic 5n2+3n+7 n2 quadratic n2+(nlogn) n2 quadratic 5n+logn3 5n linear 3logn50 3(logn) logarithmic
MUSICOMPUTATION SortingAlgorithms June,2008
Complexities
LogarithmicTime:Constant*logn LinearTime:Constant*n nlognTime PolynomialTime:nmwheremisaconstant
n2orn3orn4... quadratic,cubic,etc.
ExponentionalTime:m wheremisaconstant
2nor3nor4n..
MUSICOMPUTATION SortingAlgorithms June,2008
SortingAlgorithmComplexities
TypicallyfasterthanMergeSort
RadixSort:O(kn),wherek=numberofbins
lineartimealgorithm useslotsofspace requiresdetailedknowledgeofinput
MUSICOMPUTATION SortingAlgorithms June,2008
UsefulLinks
Descriptions en.wikipedia.org/wiki/Sort_algorithm
www.personal.kent.edu/~rmuhamma/Algorithms/algorithm.htm
AnimatedDepictionsandApplets
vision.bc.edu/~dmartin/teaching/sorting/animhtml/all.html
homepage.mac.com/mihailod/atic/sorting.html coderaptors.com/?All_sorting_algorithms