3 ms·
This got me curious and I asked ChatGPT/GPT-4 to write a sorting function for integers. It came up with the following along with a verbal explanation of how it
by aix1 4y ago
This got me curious and I asked ChatGPT/GPT-4 to write a sorting function for integers.
It came up with the following along with a verbal explanation of how it works:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
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 = [3, 6, 8, 10, 1, 2, 1]
print("Unsorted array:", arr)
sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr)
I then asked it to make the code more efficient. To this, it offered "a more efficient in-place implementation [...] using the Lomuto partition scheme". The code was reasonable but had an off-by-one error. It took me about thirty seconds to find and fix the error.
Since ChatGPT said that "the Lomuto partition scheme is generally less efficient than the Hoare partition scheme, but it is easier to implement and understand", I asked it to show the code for the Hoare scheme.
The code was correct and was accompanied by an explanation that "this version of quick sort is more efficient because it performs fewer swaps on average compared to the Lomuto partition scheme."
I asked it about the average number of swaps for both schemes. It gave some answers. However, since I didn't know the correct answers off the top of my head and couldn't be bothered to work them out, I couldn't just take ChatGPT's at face value (but I suspect that one was the correct while the other wasn't).
Finally I asked "What's the worst-case input for these three implementations?"
Here things went completely off the rails. It repeated the same answer for all there snippets. The answer happened to be correct for the last two schemes but for the first it read:
<quote>
Basic Quick Sort (with middle element as pivot):
The worst-case input for this implementation is a sorted or reverse-sorted array. Since the pivot is chosen as the middle element, the partitioning will be unbalanced, and the algorithm will have a time complexity of O(n^2).
</quote>
This is clearly nonsense.