Python Program to Implement CockTail Sort

This is a Python program to implement cocktail shaker sort.

Problem Description

The program sorts a list by cocktail shaker sort.

Problem Solution

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.

Program/Source Code

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)
Program Explanation

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.

advertisement
advertisement
Runtime Test Cases
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.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.