forked from KISHOREMUTHU/Data-Structures-And-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnext_permutation.cpp
More file actions
58 lines (40 loc) · 868 Bytes
/
next_permutation.cpp
File metadata and controls
58 lines (40 loc) · 868 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// C++ program to find the next permutation
#include<iostream>
using namespace std;
int main (){
int i,j,n;
cin >> n ; // Getting the array space
int a[n];
for(i=0;i<n;i++){
cin >> a[i];
}
int index = -1;
for(i=n-1;i>0;i--){
if(a[i] > a[i-1]){
index = i ;
break;
}
}
if(index == -1){
for(j=n-1;j>=0;j--){
cout << a[j];
}
}
else{
int pre = index;
for(j=index+1;j<n;j++){
if(a[j]>a[pre-1]&&a[j]<= a[pre]){
pre = j;
}
}
int temp = a[index -1];
a[index -1] = a[pre];
a[pre] = temp;
for(i=0;i<=index -1;i++){
cout << a[i];
}
for(i=n-1;i>=index;i--){
cout << a[i];
}
}
}