Skip to content

Commit 64330f4

Browse files
⚡️ Speed up function sorter by 439,308%
You can optimize this sorting program by using a more efficient algorithm than the bubble sort currently being used. The bubble sort has a time complexity of \(O(n^2)\), which is not efficient for large datasets. Instead, we can use Python's built-in sort function which implements Timsort, a hybrid sorting algorithm derived from merge sort and insertion sort, with a time complexity of \(O(n \log n)\). Here is the optimized program. This replacement uses Python's highly optimized built-in `sort` method, which is much faster for larger lists. The return value and functionality remain the same.
1 parent c6a201b commit 64330f4

File tree

1 file changed

+1
-6
lines changed

1 file changed

+1
-6
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
def sorter(arr):
22
print("codeflash stdout: Sorting list")
3-
for i in range(len(arr)):
4-
for j in range(len(arr) - 1):
5-
if arr[j] > arr[j + 1]:
6-
temp = arr[j]
7-
arr[j] = arr[j + 1]
8-
arr[j + 1] = temp
3+
arr.sort() # Using Python's built-in Timsort
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)