-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path-veelement.cpp
97 lines (88 loc) · 2.66 KB
/
-veelement.cpp
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/******************************************************************************
Input: -12, 11, -13, -5, 6, -7, 5, -3, -6
Output: -12 -13 -5 -7 -3 -6 11 6 5
-12 -6 -13 -5 -3 -7 5 6 11
*******************************************************************************/
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
/***************************************1st method*****************************************/
//using two pointer tc= in linear time
// void rearrange(int a[],int n){
// int l = 0;
// int r = n-1;
// while(l<=r){
// if(a[l]<0 && a[r]<0){
// l++;
// }
// else if(a[l]>0 && a[r]<0){
// swap(a[l],a[r]);
// l++;
// r--;
// }
// else if(a[l]>0 && a[r]>0){
// r--;
// }
// else{
// l++;
// r--;
// }
// }
// }
/***************************************2nd method*****************************************/
// void rearrange(int a[],int n){
// int j=0;
// for(int i=0;i<n;i++){
// if(a[i]<0){
// if(i!=j){
// swap(a[i],a[j]);
// }
// j++;
// }
// }
// }
/***************************************3rd method*****************************************/
//this method is used when we are carefull about the direction of the element also
//like even after rearanging -ve elements in begining the order is not changed.
// 5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1
// __ ,5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1
// -3, 5, 5, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1
// Loop from i = 1 to n - 1.
// a) If the current element is positive, do nothing.
// b) If the current element arr[i] is negative, we
// insert it into sequence arr[0..i-1] such that
// all positive elements in arr[0..i-1] are shifted
// one position to their right and arr[i] is inserted
// at index of first positive element.
void rearrange(int a[],int n){
int key,j;
for(int i=1;i<n;i++){
key = a[i];
//if key is +ve
if(key > 0){
continue;
}
//if key is -ve
//then right shift all
j = i-1;
while(j >= 0 && a[j] > 0){
a[j+1] = a[j];
j--;
}
a[j+1] = key;
}
}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
rearrange(a,n);
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
}