Skip to content

Commit

Permalink
Merge pull request #1536 from YASH01009/YASH01009_NPERM_C++
Browse files Browse the repository at this point in the history
Next Largest Permutation added in C++
  • Loading branch information
shraddhavp authored Dec 16, 2020
2 parents dc92b0a + 9d7c958 commit 44732ef
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions C-Plus-Plus/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
- [Z Algorithm](cp/zalgorithm.cpp)
- [ArraySub](cp/ARRAYSUB.cpp)
- [Suduko Solver](cp/SudukoSolver.cpp)
- [Next Largest Permutation](cp/NextPermutation.cpp)

## Data Structures

Expand Down
53 changes: 53 additions & 0 deletions C-Plus-Plus/cp/NextPermutation.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
Given an array, fing the next lexicographical largest permutation
**/

#include <bits/stdc++.h>
using namespace std;

vector<int> nextPermutation(vector<int> &A) {
int k = A.size()-1;
while(A[k-1] >= A[k] && k > 0)
k--;
if(k == 0)
reverse(A.begin(), A.end());
else {
int t = A[k-1];
int m = k;
for(int i=k+1; i<A.size(); i++)
if(A[i] > t && A[i] < A[k])
m = i;
A[k-1] = A[m];
A[m] = t;
sort(A.begin()+k, A.end());
}
return A;
}

int main() {
int n;
cin >> n;
vector<int> arr(n);
for(int i = 0; i < n; i++)
cin >> arr[i];
nextPermutation(arr);
cout << "The next permutation of the array is : \n";
for(int i = 0; i < n; i++)
cout << arr[i] << ' ';
cout << '\n';
return 0;
}

/**
Input :
6
5 3 4 9 7 6
Output :
6
5 3 4 9 7 6
Time Complexity : O(nlogn)
Space Complexity : O(n)
**/

0 comments on commit 44732ef

Please sign in to comment.