From 32e36d05ff32759ed0ebdbdef0edfaf78fce184e Mon Sep 17 00:00:00 2001 From: Abhishek Mehra <52788025+Triaro@users.noreply.github.com> Date: Fri, 2 Oct 2020 11:07:59 +0530 Subject: [PATCH] Create cocktail_sort.m Sorting Algorithm --- algorithms/sorting/cocktail_sort.m | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 algorithms/sorting/cocktail_sort.m diff --git a/algorithms/sorting/cocktail_sort.m b/algorithms/sorting/cocktail_sort.m new file mode 100644 index 0000000..572a4fe --- /dev/null +++ b/algorithms/sorting/cocktail_sort.m @@ -0,0 +1,30 @@ +function list = cocktailSort(list) + + %since the do-while loop doesn't exist in MATLAB we will perform following steps + swapped = true; + + while swapped + + %Bubble sort down the list + swapped = false; + for i = (1:numel(list)-1) + if( list(i) > list(i+1) ) + list([i i+1]) = list([i+1 i]); %swap + swapped = true; + end + end + + if ~swapped + break + end + + %Bubble sort up the list + swapped = false; + for i = (numel(list)-1:-1:1) + if( list(i) > list(i+1) ) + list([i i+1]) = list([i+1 i]); %swap + swapped = true; + end %if + end %for + end %while +end %cocktail sort