diff --git a/Data Structures and Algorithms/README.md b/Data Structures and Algorithms/README.md index ca9c727f..29a0afc6 100644 --- a/Data Structures and Algorithms/README.md +++ b/Data Structures and Algorithms/README.md @@ -8,6 +8,8 @@ - Bogo Sort +- Cocktail Sort + - Counting Sort - Linear search (for numbers) @@ -36,6 +38,8 @@ - Recursive Binary Search +- Shell Sort + - Selection Sort - Binary Tree traversal diff --git a/Data Structures and Algorithms/Sorting Algorithms/cocktail_sort.py b/Data Structures and Algorithms/Sorting Algorithms/cocktail_sort.py new file mode 100644 index 00000000..6807ce99 --- /dev/null +++ b/Data Structures and Algorithms/Sorting Algorithms/cocktail_sort.py @@ -0,0 +1,27 @@ +import sys + +def cocktail_sort(arr): + n = len(arr) + swapped = True + start = 0 + end = n - 1 + while swapped: + swapped = False + + for i in range(start, end): + if arr[i] > arr[i + 1]: + arr[i], arr[i + 1] = arr[i + 1], arr[i] + swapped = True + if not swapped: + break + swapped = False + end -= 1 + + for i in range(end - 1, start - 1, -1): + if arr[i] > arr[i + 1]: + arr[i], arr[i + 1] = arr[i + 1], arr[i] + swapped = True + start += 1 + return arr + +print(cocktail_sort([5, 8, 1, 4, 7, 9, 6, 3, 2])) diff --git a/Data Structures and Algorithms/Sorting Algorithms/shell_sort.py b/Data Structures and Algorithms/Sorting Algorithms/shell_sort.py new file mode 100644 index 00000000..d84fbb29 --- /dev/null +++ b/Data Structures and Algorithms/Sorting Algorithms/shell_sort.py @@ -0,0 +1,18 @@ +def shell_sort(arr): + n = len(arr) + gap = n // 2 # gap size + + while gap > 0: + for i in range(gap, n): + temp = arr[i] + j = i + # Perform insertion sort for the elements separated by the gap + while j >= gap and arr[j - gap] > temp: + arr[j] = arr[j - gap] + j -= gap + arr[j] = temp + gap //= 2 + + return arr + +print(shell_sort([5, 8, 1, 4, 7, 9, 6, 3, 2]))