Implementing Quick Sort Algorithm in Python

Discussion in 'Programming/Scripts' started by lexie21, Jul 18, 2023.

  1. lexie21

    lexie21 New Member

    I'm currently working on implementing the Quick Sort algorithm in Python, but I'm encountering some issues with my code. I've tried to follow the standard implementation, but it seems to produce incorrect results. Can someone please review my code and help me identify the problem?

    Here is the Code:
    def quick_sort(arr):
        if len(arr) <= 1:
            return arr
        pivot = arr[0]
        less_than_pivot = [x for x in arr[1:] if x <= pivot]
        greater_than_pivot = [x for x in arr[1:] if x > pivot]
        return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot)
    # Example usage:
    my_array = [8, 4, 2, 9, 5, 1, 6]
    sorted_array = quick_sort(my_array)
    I expected the code to sort the array in ascending order using the Quick Sort algorithm. However, the output I'm getting is incorrect. I have read a few articles about the Quicksort algorithm on scaler, but I am still unable to understand where I am going wrong. I would appreciate any insights or suggestions on what could be causing the issue and how to resolve it. Thank you.
    Note: Please provide any code-based explanations or suggestions to help me understand and debug the problem effectively.
  2. Taleman

    Taleman Well-Known Member HowtoForge Supporter

    Is this your homework from school?
    So, what is the output?
    What is the standard implementation you tried to follow? I do not understand the code you show, it does not look like usual way to do quicksort.
    If you just want a sorting function, bubble sort is easier to write.

Share This Page