PRACTICAL NO
PRACTICAL NO
Algorithms:
1. MERGE_SORT(arr, beg, end)
2. if beg < end
3. set mid = (beg + end)/2
4. MERGE_SORT(arr, beg, mid)
5. MERGE_SORT(arr, mid + 1, end)
6. MERGE (arr, beg, mid, end)
7. end of if
8. END MERGE_SORT
Programs:
def merge_sort(arr):
# If the array has more than 1 element
if len(arr) > 1:
mid = len(arr) // 2 # Find the middle of the list
left_half = arr[:mid] # Divide the elements into two halves
right_half = arr[mid:]
# Merge the temp arrays back into the original array arr
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
print(f"Merging: {arr}")
def main():
# Take input from the user
arr = list(map(int, input("Enter the list of numbers (space-separated): ").split()))
print(f"Original array: {arr}"
# Perform Merge Sort
merge_sort(arr)
print(f"Sorted array: {arr}")
if _name_ == "_main_":
main()
Output:
PRACTICAL NO-5
OBJECT:WAP for Quick Sort.
Theory:
Quick sort is a sorting algorithm that uses a divide-and-conquer strategy to sort an array. It
works by:
• Selecting a pivot: Choosing a value in the array to be the pivot element
• Partitioning: Ordering the remaining elements so that values smaller than the pivot
are on the left and values larger than the pivot are on the right
• Repeating: Recursively applying these steps to the sub-arrays on either side of the
pivot until the sub-arrays are too small to be sorted
Quick sort is considered one of the most efficient sorting algorithms, along with Merge
Sort. It's useful for sorting large data sets.
The complexity of the Quick Sort algorithm is:
• Average case: O(n*log(n))
• Best case: O(n*log(n))
• Worst case: O(n^2)
• Space complexity: O(n log n)
Algoritms:
1. QUICKSORT (array A, start, end)
2. {
3. 1 if (start < end)
4. 2 {
5. 3 p = partition(A, start, end)
6. 4 QUICKSORT (A, start, p - 1)
7. 5 QUICKSORT (A, p + 1, end)
8. 6 }
9. }
Programs:
def quick_sort(arr, low, high):
if low < high:
# Partitioning index
pi = partition(arr, low, high)
# Rearrange the array so that elements smaller than the pivot are on the left
# and elements greater than the pivot are on the right
for j in range(low, high):
if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i] # Swap
def main():
# Take input from the user
arr = list(map(int, input("Enter the list of numbers (space-separated): ").split()))
print(f"Original array: {arr}")
if _name_ == "_main_":
main()
Output: