Docsity

Sorting Algorithms: Bubble, Modified Bubble, Insertion, Selection, Merge, Heap, Quicksort, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Sorting Algorithms: Bubble, Modified Bubble, Insertion, Selection, Merge, Heap, Quicksort and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Bubble Sort

for i = n downto 2 do for j = 1 to i-1 do if A[j] > A[j+1] then A[j] โ†” A[j+1] end if end for end for

for i = n downto 2 do for j = 1 to i-1 do if A[j] > A[j+1] then A[j] โ†” A[j+1] end if end for end for

Bubble Sort (Modified)

i โ† n- while i > 0 do t โ† 1 for j = 1 to i do if A[j] > A[j+1] then A[j] โ†” A[j+1] t โ† j end if end for i โ† t- end while

Cocktail-Shaker Sort

No code.

Insertion Sort (without sentinel)

for i = 2 to n do t โ† A[i] j โ† i- while j>0 and A[j]>t do A[j+1] โ† A[j] j โ† j- end while A[j+1] โ† t end for

for i = 2 to n do t โ† A[i] j โ† i- while j>0 and A[j]>t do A[j+1] โ† A[j] j โ† j- end while A[j+1] โ† t end for

Selection Sort

for i = n downto 2 do k โ† 1 for j = 2 to i do if A[j] > A[k] then k โ† j end for A[k] โ†” A[i] end for

for i = n downto 2 do k โ† 1 for j = 2 to i do if A[j] > A[k] then k โ† j end for A[k] โ†” A[i] end for

Heap Sort

proc heapsort(A: list, n: list size) {Create heap} for r = bn/2c downto 1 do sift(r,n) end for {Finish Sort} for m = n downto 2 do A[1] โ†” A[m] sift(1,m-1) end for end proc

proc sift(p: root, m: size of list) c โ† 2p while c โ‰ค m do if c < m then if A[c+1] > A[c] then c โ† c+1 end if end if if A[c] > A[p] then A[p] โ†” A[c] p โ† c c โ† 2p else exit while loop end if end while end proc

Quicksort

procedure quicksort(A,p,r) if p<r then q โ† partition(A,p,r) quicksort(A,p,q-1) quicksort(A,q+1,r) end if end procedure

function partition(A,p,r) X โ† A[r] i โ† p- for j = p to r-1 do if A[j] โ‰ค X then i โ† i+ A[i] โ†” A[j] end if end for A[i+1] โ†” A[r] return(i+1) end function