Professional Documents
Culture Documents
class AVLNode:
self.key = key
self.height = 1
self.left = None
self.right = None
class AVLTree:
def __init__(self):
self.root = None
if not node:
return AVLNode(key)
else:
balance = self._get_balance(node)
return self._right_rotate(node)
return self._left_rotate(node)
node.left = self._left_rotate(node.left)
return self._right_rotate(node)
node.right = self._right_rotate(node.right)
return self._left_rotate(node)
return node
y = z.right
t2 = y.left
# Perform rotation
y.left = z
z.right = t2
# Update heights
return y
y = z.left
t3 = y.right
# Perform rotation
y.right = z
z.left = t3
# Update heights
EXP9
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
# Test case
arr = [5, 2, 9, 3, 7, 4, 1, 8, 6, 0]
sorted_arr = quick_sort(arr)
print(sorted_arr)
quick_sort(list(range(10000, 0, -1)))
end_time = time.time()
Pseudocode:
quick_sort(arr)
if length(arr) <= 1:
return arr
else:
else:
sorted_left = quick_sort(left)
sorted_right = quick_sort(right)
Choosing a pivot element: This operation takes constant time, i.e., O(1).
Partitioning the array: This operation takes linear time, i.e., O(n), where n is the size of the array. In the worst case, if the
pivot element is either the smallest or largest element in the array, then the partitioning operation will not divide the
array into two subarrays of equal size. In this case, the partitioning operation takes O(n) time.
Recursively sorting the two subarrays: This operation involves recursive calls to the quick_sort function on subarrays of
size less than n. The number of recursive calls depends on the size of the subarrays and the pivot element chosen. In the
average case, the subarrays are divided into roughly equal sizes, and the number of recursive calls is logarithmic, i.e.,
O(log(n)). However, in the worst case, the subarrays are of size n-1 and 1, and the number of recursive calls is n-1.
Therefore, the worst-case time complexity of this operation is O(n^2).
Concatenating the two sorted subarrays and the pivot element: This operation takes linear time, i.e., O(n), where n is the
size of the array.
Therefore, the overall time complexity of the Quick Sort Algorithm is O(n*log(n)) in the average case and O(n^2) in the
worst case. The worst case occurs when the pivot element is either the smallest or largest element in the array, and the
subarrays are not divided into roughly equal sizes. However, in practice, Quick Sort is a very efficient algorithm and is
widely used in industry.
EXP 10
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
left_half = merge_sort(left_half)
right_half = merge_sort(right_half)
left_index = right_index = 0
merged.append(left[left_index])
left_index += 1
else:
merged.append(right[right_index])
right_index += 1
merged += left[left_index:]
merged += right[right_index:]
return merge:
sorted_arr = merge_sort(arr)
print(sorted_arr)
CODES
EXP 8
EXP 9
EXP 10