This is a Python program to implement cocktail shaker sort.
The program sorts a list by cocktail shaker sort.
1. Create a function cocktail_shaker_sort that takes a list as argument.
2. Set upper to length of the list – 1 and lower to 0.
3. Create a loop inside which bubble sort is performed on the list from indexes lower to upper and then from upper to lower.
4. After bubble sort is performed from indexes lower to upper, decrement upper and after it has been performed from upper to lower, increment lower.
5. Check if no swaps were performed in any iteration. If there were no swaps, then the list is sorted.
Here is the source code of a Python program to implement cocktail shaker sort. The program output is shown below.
def cocktail_shaker_sort(alist): def swap(i, j): alist[i], alist[j] = alist[j], alist[i] upper = len(alist) - 1 lower = 0 no_swap = False while (not no_swap and upper - lower > 1): no_swap = True for j in range(lower, upper): if alist[j + 1] < alist[j]: swap(j + 1, j) no_swap = False upper = upper - 1 for j in range(upper, lower, -1): if alist[j - 1] > alist[j]: swap(j - 1, j) no_swap = False lower = lower + 1 alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] cocktail_shaker_sort(alist) print('Sorted list: ', end='') print(alist)
1. The user is prompted to enter a list of numbers.
2. The list is passed to the cocktail_shaker_sort function.
3. The sorted list is displayed.
Case 1: Enter the list of numbers: 3 18 5 2 10 0 7 4 Sorted list: [0, 2, 3, 4, 5, 7, 10, 18] Case 2: Enter the list of numbers: 6 5 4 3 2 Sorted list: [2, 3, 4, 5, 6] Case 3: Enter the list of numbers: 2 Sorted list: [2]
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Apply for Python Internship
- Check Information Technology Books
- Apply for Programming Internship
- Check Python Books
- Practice Programming MCQs