comb sort

Solutions on MaxInterview for comb sort by the best coders in the world

showing results for - "comb sort"
Ivanna
02 Feb 2017
1def combsort_inplace(data):
2    length = len(data)
3    shrink = 1.3
4    _gap = length
5    sorted = False
6    while not sorted:
7        # Python has no builtin 'floor' function, so we/I just have one variable (_gap) to be shrunk,
8        # and an integer variable (gap) to store the truncation (of the other variable) in and
9        # to use for stuff pertaining to indexing
10        _gap /= shrink
11        # gap = np.floor(_gap)
12        gap = int(_gap)
13        if gap <= 1:
14            sorted = True
15            gap = 1
16        # equivalent to `i = 0; while (i + gap) < length: ...{loop body}... i += 1`
17        for i in range(length - gap):
18            sm = gap + i
19            if data[i] > data[sm]:
20                # because Python is very nice, this accomplishes the swap
21                data[i], data[sm] = data[sm], data[i]
22                sorted = False
23
24
25def combsort(data):
26    length = len(data)
27    shrink = 1.3
28    _gap = length
29    out = list(data)
30    is_sorted = False
31    while not is_sorted:
32        _gap /= shrink
33        gap = int(_gap)
34        if gap <= 1:
35            is_sorted = True
36            gap = 1
37        for i in range(length - gap):
38            sm = gap + i
39            if out[i] > out[sm]:
40                out[i], out[sm] = out[sm], out[i]
41                is_sorted = False
42    return out
queries leading to this page
comb sortcomb sort