Lab 08 Elementary Sorting Algorithms and Searching: Data Structures CS218 Instructor: Anam Qureshi
Lab 08 Elementary Sorting Algorithms and Searching: Data Structures CS218 Instructor: Anam Qureshi
Algorithm Bubble_Sort(A)
Input: An array of size n
Output: Sorted array
For(i=0 to n-1) do
For(j=0 to n-1-i) do
if(a[j] > a[j+1]) then
Swap(a[j],a[j+1])
end if
end for
End for
Selection Sort
• It is a simple algorithm
• Inefficient for large number of inputs
• Repeatedly finds the minimum element and
insert it into the sorted sub array.
• Working principle of selection sort
Implementation Details of Selection
Sort
Algorithm Selection_Sort(A)
Input: An array of size n
Output: Sorted array
For(i=0 to A.size) do
min_value=i
for(j=i+1 to A.size) do
if(A[j] < A [min_value]) then
min_value= j
end if
end for
swap(A[min_value], A[j])
End for
Insertion Sort
• Insertion sort performs faster than bubble sort
• It works the same way as organization of play
cards
• Pick an element from unsorted list and insert
it at the correct position
• Working principle of insertion sort
Implementation Details of Insertion
Sort
Algorithm Insertion_Sort(A)
Input: An array of size n
Output: Sorted Array
for (j = 1 to A.size) do
temp = A[j]
i = j-1
while (i>=0 && A[i] > temp) do
A[i+1] = A[i]
i = i-1
end while
A[i+1] = temp
End for
Shell Sort
• It is a variation of insertion sort
• It starts sorting pairs of element far apart from
each other
• By the end, the gap is reduced to 1
– It will act like insertion sort algorithm
• Working principle
Implementation Details of Shell Sort
Algorithm Shell_Sort(A)
Input: An array of size n
Output: Sorted Array
for (gap = n/2 ; gap > 0 ; gap/=2) do
for (i= gap ; i < n; i+=1) do
temp= A[i]
for(j=i ; j >= gap && A[j-gap] > temp ; j-=gap) do
A[j] = A[ j - gap]
end for
A[j]= temp
end for
End for
Properties of Sorting Algorithms
Property Description