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

Function circle_sort

sorts/circle_sort.py:12–80  ·  view source on GitHub ↗

A pure Python implementation of circle sort algorithm :param collection: a mutable collection of comparable items in any order :return: the same collection in ascending order Examples: >>> circle_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> circle_sort([]) [] >>> circl

(collection: list)

Source from the content-addressed store, hash-verified

10
11
12def circle_sort(collection: list) -> list:
13 """A pure Python implementation of circle sort algorithm
14
15 :param collection: a mutable collection of comparable items in any order
16 :return: the same collection in ascending order
17
18 Examples:
19 >>> circle_sort([0, 5, 3, 2, 2])
20 [0, 2, 2, 3, 5]
21 >>> circle_sort([])
22 []
23 >>> circle_sort([-2, 5, 0, -45])
24 [-45, -2, 0, 5]
25 >>> collections = ([], [0, 5, 3, 2, 2], [-2, 5, 0, -45])
26 >>> all(sorted(collection) == circle_sort(collection) for collection in collections)
27 True
28 """
29
30 if len(collection) < 2:
31 return collection
32
33 def circle_sort_util(collection: list, low: int, high: int) -> bool:
34 """
35 >>> arr = [5,4,3,2,1]
36 >>> circle_sort_util(lst, 0, 2)
37 True
38 >>> arr
39 [3, 4, 5, 2, 1]
40 """
41
42 swapped = False
43
44 if low == high:
45 return swapped
46
47 left = low
48 right = high
49
50 while left < right:
51 if collection[left] > collection[right]:
52 collection[left], collection[right] = (
53 collection[right],
54 collection[left],
55 )
56 swapped = True
57
58 left += 1
59 right -= 1
60
61 if left == right and collection[left] > collection[right + 1]:
62 collection[left], collection[right + 1] = (
63 collection[right + 1],
64 collection[left],
65 )
66
67 swapped = True
68
69 mid = low + int((high - low) / 2)

Callers 1

circle_sort.pyFile · 0.85

Calls 1

circle_sort_utilFunction · 0.85

Tested by

no test coverage detected