Professional Documents
Culture Documents
Lab # 04
Sorting Operation in an Array Bubble Sort Algorithm
EXERCISE: Attach all [code and outputs] printouts here
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]
for i in range(n-1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
recursive_bubble_sort(arr, n-1)
3. Select any other sorting algorithm and implement. Assume A[]={ 9,7,5,11,12,2,14,3,10,6}
INPUT CODE
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i+1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] =
arr[min_index], arr[i]
# Assuming array A
A = [9, 7, 5, 11, 12, 2, 14, 3, 10, 6]
selection_sort(A)
print("Sorted Array (Selection Sort):", A)
When analyzing the time complexity, we focus on the dominant term, so the worst-case
time complexity of recursive bubble sort is O(n2).
Analysis:
Bubble Sort:
Best Case: O(n) (when the array is already sorted)
Worst Case: O(n^2)
Best Bound: O(n)
Worst Bound: O(n^2)
Conclusion: Simple to understand, but inefficient for large datasets.
Selection Sort:
Best Case: O(n^2)
Worst Case: O(n^2)
Best Bound: O(n^2)
Worst Bound: O(n^2)
Conclusion: More efficient than bubble sort for large datasets, but still has a high
time complexity.
Consider using more efficient sorting algorithms like Merge Sort or Quick Sort for
better performance in practical scenarios.
SE-22063 LAB -4