diff --git a/Algorithm/Searching_Sorting/readme.md b/Algorithm/Searching_Sorting/readme.md index a750add6e..01176ad92 100644 --- a/Algorithm/Searching_Sorting/readme.md +++ b/Algorithm/Searching_Sorting/readme.md @@ -73,6 +73,7 @@ Following are the types of searches which we will be discussing in this book. * Linear Search ----> [Python](/Code/Python/linearsearch.py) * Merge Sort ----> [C++](/Code/C++/merge_sort.cpp) * Number of times sorted array rotated ---->[C++](/Code/C++/no_of_rotation.cpp) +* Pancake Sort ----> [C++](https://github.com/Ayush12062000/Algo-Tree/blob/issue-1059/Code/C%2B%2B/Pancake_sort.cpp) * Painter's Partition -->[C++](/Code/Python/Painter's_Partition.py) * Quick Sort ----> [C++](/Code/C++/quick_sort.cpp) * Rabin Karp Algorithm ----> [C++](/Code/C++/rabin_karp.cpp) diff --git a/Code/C++/Pancake_sort.cpp b/Code/C++/Pancake_sort.cpp new file mode 100644 index 000000000..cf622bbf2 --- /dev/null +++ b/Code/C++/Pancake_sort.cpp @@ -0,0 +1,88 @@ +/* + PANCAKE SORT + - Sorting the sequence by making minimum reversals +*/ +#include +#define scan(arr,n) for(int i=0;i>arr[i]; +#define input(n) int n; cin>>n; +using namespace std; + +// function to reverse the array by flipping elemenets +void flip(int arr[], int n) +{ + int temp, i = 0; + while (i < n) + { + temp = arr[i]; + arr[i] = arr[n]; + arr[n] = temp; + i++;n--; + } +} + +// function that returns index of maximum element. +int Maximum_element(int arr[],int n) +{ + int mi=0,maxi=INT_MIN; + for(int i=0;i maxi) + { + maxi = arr[i]; + mi=i; + } + } + return mi; +} + +void Pancake_sort(int arr[],int n) +{ + int maxi_index=0; + for(int current_size = n; current_size>1;current_size--) // decreasing the size of array by 1 each time. + { + maxi_index = Maximum_element(arr,current_size); //finding the index of maximum element. + + if(maxi_index != current_size-1) // checking if index of maximum element is not equal to current array size. + { + flip(arr,maxi_index); // flipping or reversing the array from start till the index of max element. + flip(arr,current_size-1); // flipping or reversing the array from start till the decreased array size. + } + } +} + +int main() +{ + input(n); //enter number of elements in an array + int arr[n]; + scan(arr,n); // enter n elements in array + + Pancake_sort(arr,n); // calling Pancake sort function + + for(int i=0;i