From bc11c85267fbf3c6a7e00edb57308ddbb9b7a0c1 Mon Sep 17 00:00:00 2001 From: Ekta kanojia <91015183+Ektakanojia@users.noreply.github.com> Date: Wed, 27 Oct 2021 18:28:31 +0530 Subject: [PATCH] chore(CPlusPlus): add next permutation (#621) --- .../CPlusPlus/Arrays/next-permutation.cpp | 71 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 3 +- 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 algorithms/CPlusPlus/Arrays/next-permutation.cpp diff --git a/algorithms/CPlusPlus/Arrays/next-permutation.cpp b/algorithms/CPlusPlus/Arrays/next-permutation.cpp new file mode 100644 index 00000000..2469718f --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/next-permutation.cpp @@ -0,0 +1,71 @@ +//c++ program to find the next greatest permutation of given number. +//Sample input 1 : +//nums =[1,2,3] +//sample output 1: +// nums =[1,3,2] +//sample input 2: +//nums =[3,2,1] +//sample output: +//nums =[1,2,3] +//time complexity:O(n). +//space complexity:O(1),because we are doing in place. +#include +using namespace std; + vectornextPermutation(int n,vectornums) { + + int k; + int change=-1; + //Base case if vector have size either 0 or 1 element. + if(nums.size()==0 || nums.size()==1) + return nums; + //Base Case if vector have size 2,simply reverse them suppose we have nums=[1,2] then output will be [2,1]. + if(nums.size()==2) + { + reverse(nums.begin(),nums.end()); + + } + //case where the size of vector is greater the 2 start traversing from the right side + // While going from right to left, if we find an index whose value is less than index at right + // changes in permutation starts from that index. + for(k=nums.size()-2;k>=0;k--) + { + if(nums[k]change;k--) + { + if(nums[k]-nums[change]>0) + { + swap(nums[k],nums[change]); + break; + } + + } + //After swapping we are just sort the values from change+1 index to n-1 index. + reverse(nums.begin()+change+1,nums.end()); + return nums; + } +int main() +{ + int n = 6; + vectorv{5,3,4,9,7,6}; + vector res; + res = nextPermutation(n, v); + for (int i = 0; i < res.size(); i++) { + cout << res[i] << " "; + } +} + diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index baa07a9c..cc612f9b 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -25,9 +25,10 @@ - [Index of Smallest element of Array](Arrays/index-of-smallest-element-of-array.cpp) - [Move Zeros to End of The Array](Arrays/move-zeros-to-end-of-array.cpp) - [Kadane's Algorithm](Arrays/Kadane's-Algorithm.cpp) +- [All unique triplet that sum up to given value](Arrays/three-sum.cpp) - [Merge two sorted array without using extraspace](Arrays/merge-two-sorted-array.cpp) - [All unique triplet that sum up to given value](Arrays/three-sum.cpp) - +- [Next permutation](Arrays/next-permutation.cpp) ## Dynamic-Programming - [Longest Common Subsequence](Dynamic-Programming/longest-common-subsequence.cpp)