write a python code to sort an array in linear time
- User
write a python code to sort an array in linear time
Assistant
Here is a Python code to sort an array in linear time:
array = [5, 2, 3, 1, 4] for i in range(1, len(array)): j = i while j > 0 and array[j] < array[j-1]: array[j], array[j-1] = array[j-1], array[j] j -= 1 print(array) # [1, 2, 3, 4, 5]This is a linear time sorting algorithm called Bubble Sort. It works by repeatedly swapping adjacent elements if they are in the wrong order.
On each pass, the largest element "bubbles" up to the end. Hence the name - Bubble Sort.
Time complexity: O(n) for best and average case. Worst case is O(n^2).
Space complexity: O(1), since no extra space is used.
Hope this helps! Let me know if you have any other questions.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.