Skip to content

Partition Set of the Quicksort Algorithm #5

@illenium-design

Description

@illenium-design

It looks like you are trying to implement the partition step of the quicksort algorithm in Python. There are some syntax errors and minor issues in your code. Here's a corrected version:

def partition(numbers, i, k):
    midpoint = i + (k - i) // 2
    pivot = numbers[midpoint]
    
    done = False
    l = i
    h = k

    while not done:
        while numbers[l] < pivot:
            l = l + 1
        while pivot < numbers[h]:
            h = h - 1
        
        if l >= h:
            done = True
        else:
            # Swap elements at l and h
            temp = numbers[l]
            numbers[l] = numbers[h]
            numbers[h] = temp
            l = l + 1
            h = h - 1
    
    return h

# Example usage:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
i = 0
k = len(numbers) - 1
partition_index = partition(numbers, i, k)
print("Partitioned array:", numbers)
print("Partition index:", partition_index)

Changes made:

  1. Corrected the capitalization of midpoint and pivot.
  2. Replaced numbers(midpoint) with numbers[midpoint] to correctly access the element at the midpoint.
  3. Fixed the indentation of the code.
  4. Added a swap step inside the loop to properly partition the array.

This corrected code should help you partition the array using the quicksort algorithm.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions