Comb sort is an improvement over bubble sort. It eliminates small values near the end of the list that slow down the sorting process. Comb sort works by comparing and swapping elements separated by a gap, which reduces progressively until the list is sorted. The algorithm aims to reduce the number of comparisons by jumping over multiple elements in each pass.
Consider an array with the following elements:
[8, 4, 1, 56, 3, -44, 23, -6, 28, 0]
To sort this array using comb sort, follow these steps:
Let's apply these steps to the example array:
Below is the pseudo code for the comb sort algorithm:
function combSort(array)
n = length(array)
gap = n
shrink = 1.3
sorted = false
while not sorted do
gap = floor(gap / shrink)
if gap <= 1 then
gap = 1
sorted = true
end if
i = 0
while i + gap < n do
if array[i] > array[i + gap] then
swap(array[i], array[i + gap])
sorted = false
end if
i = i + 1
end while
end while
end function
Explanation:
def comb_sort(arr):
n = len(arr)
gap = n
shrink = 1.3
sorted = False
while not sorted:
gap = int(gap / shrink)
if gap <= 1:
gap = 1
sorted = True
i = 0
while i + gap < n:
if arr[i] > arr[i + gap]:
arr[i], arr[i + gap] = arr[i + gap], arr[i]
sorted = False
i += 1
return arr
# Example usage:
array = [8, 4, 1, 56, 3, -44, 23, -6, 28, 0]
print("Original array:", array)
sorted_array = comb_sort(array)
print("Sorted array:", sorted_array) # Output: [-44, -6, 0, 1, 3, 4, 8, 23, 28, 56]
This Python program defines a function to perform comb sort on an array. The function initializes the gap and progressively reduces it while comparing and swapping elements until the array is sorted.