*PYTHON* The following algorithm is known as bubble sort . The following structu
ID: 3710171 • Letter: #
Question
*PYTHON*
The following algorithm is known as bubble sort. The following structure shows the indention structure of this algorithm. Ensure to implement your code following this structure.
While the list is not sorted
For each adjacent pair of elements
If the pair is not sorted
Swap its elements
Now, implement this bubble sort algorithm and test its performance. You should submit two files. The first is the implementation of this algorithm and the second file is the performance of measurement of this algorithm.
Once you have your performance measurement of bubble sort algorithm available (i.e., executing your file 2), compare to performance measurement of selectionsort algorithm and let me know which algorithm is more effective.
Explanation / Answer
# function for bubble sort in python
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
#function for selection sort in python
def selectionSort(A):
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
##--------------------------------------------------------------##
For measuring performance of bubble sort, here is the code:
import time
array = [1,1,2,3,4,3,77,55,44,3,2,1]
start = time.time()
bubbleSort(array)
end = time.time()
print ("time taken: ", str(end-start))
##---------------------------------------##
You can run the same code for selectionSort and compare the run times for both the algorithms
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.