My QA Projects

QA Projects I was involded.

View on GitHub

Merge Sort with list

def merge_sort(arr):
    if len(arr) > 1:
        
        # Finding the mid of the array
        mid = len(arr) // 2
        
        # Dividing the elements into 2 halves
        left_half = arr[:mid]
        right_half = arr[mid:]
        
        # Recursive call on each half
        merge_sort(left_half)
        merge_sort(right_half)
        
        # Merge the two halves into sorted order
        i = j = k = 0
        
        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
        
        # Checking if any element was left
        while i < len(left_half):
            arr[k] = left_half[i]
            i += 1
            k += 1
        
        while j < len(right_half):
            arr[k] = right_half[j]
            j += 1
            k += 1

# Example usage:
arr = [12, 11, 13, 5, 6, 7]
merge_sort(arr)

print("Sorted array:", arr)

Step 1: We define a function merge_sort that takes an input list arr.

Step 2: The function first checks if the length of arr is greater than 1, indicating there are elements to sort.

Step 3: It calculates the middle index mid of the array and divides arr into two halves: left_half and right_half.

Step 4: The function recursively calls merge_sort on each half until the base case (single element or empty array) is reached.

Step 5: After sorting both halves, the merge function merges the two sorted halves back into the original array arr.

Step 6: The merge process compares elements from left_half and right_half, placing them in sorted order into arr.

5. Quick Sort:

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    
    pivot = arr[len(arr) // 2]  # Choosing the middle element as the pivot
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    
    return quick_sort(left) + middle + quick_sort(right)

# Example usage:
arr = [12, 11, 13, 5, 6, 7]
sorted_arr = quick_sort(arr)

print("Sorted array:", sorted_arr)

Step 1: We define a function quick_sort that takes an input list arr. Step 2: If the length of arr is 1 or less, it simply returns arr (base case for recursion). Step 3: he pivot element is chosen as arr[len(arr) // 2], which is the middle element in this implementation. Step 4: We create three sub-lists (left, middle, and right) using list comprehensions: