MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / double_sort

Function double_sort

sorts/double_sort.py:4–37  ·  view source on GitHub ↗

This sorting algorithm sorts an array using the principle of bubble sort, but does it both from left to right and right to left. Hence, it's called "Double sort" :param collection: mutable ordered sequence of elements :return: the same collection in ascending order Examples:

(collection: list[Any])

Source from the content-addressed store, hash-verified

2
3
4def double_sort(collection: list[Any]) -> list[Any]:
5 """This sorting algorithm sorts an array using the principle of bubble sort,
6 but does it both from left to right and right to left.
7 Hence, it's called "Double sort"
8 :param collection: mutable ordered sequence of elements
9 :return: the same collection in ascending order
10 Examples:
11 >>> double_sort([-1 ,-2 ,-3 ,-4 ,-5 ,-6 ,-7])
12 [-7, -6, -5, -4, -3, -2, -1]
13 >>> double_sort([])
14 []
15 >>> double_sort([-1 ,-2 ,-3 ,-4 ,-5 ,-6])
16 [-6, -5, -4, -3, -2, -1]
17 >>> double_sort([-3, 10, 16, -42, 29]) == sorted([-3, 10, 16, -42, 29])
18 True
19 """
20 no_of_elements = len(collection)
21 for _ in range(
22 int(((no_of_elements - 1) / 2) + 1)
23 ): # we don't need to traverse to end of list as
24 for j in range(no_of_elements - 1):
25 # apply the bubble sort algorithm from left to right (or forwards)
26 if collection[j + 1] < collection[j]:
27 collection[j], collection[j + 1] = collection[j + 1], collection[j]
28 # apply the bubble sort algorithm from right to left (or backwards)
29 if collection[no_of_elements - 1 - j] < collection[no_of_elements - 2 - j]:
30 (
31 collection[no_of_elements - 1 - j],
32 collection[no_of_elements - 2 - j],
33 ) = (
34 collection[no_of_elements - 2 - j],
35 collection[no_of_elements - 1 - j],
36 )
37 return collection
38
39
40if __name__ == "__main__":

Callers 1

double_sort.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected