Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRearrangePositiveNegative.java
More file actions
Latest commit
45 lines (36 loc) · 1.34 KB
/
Copy pathRearrangePositiveNegative.java
File metadata and controls
45 lines (36 loc) · 1.34 KB
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
importjava.util.Scanner;
publicclassRearrangePositiveNegative {
publicstaticvoidmain(String[] args) {
Scannerscanner = newScanner(System.in);
System.out.println("Rearrange Positive and Negative Numbers");
System.out.println("--------------------------------------");
System.out.print("Enter the size of the array: ");
intsize = scanner.nextInt();
int[] arr = newint[size];
System.out.println("Enter " + size + " integers:");
for (inti = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
rearrangeArray(arr);
System.out.println("Rearranged array:");
for (intnum : arr) {
System.out.print(num + " ");
}
scanner.close();
}
privatestaticvoidrearrangeArray(int[] arr) {
intj = 0; // Position to place the next negative number
for (inti = 0; i < arr.length; i++) {
if (arr[i] < 0) {
// If current element is negative, swap it with the
// element at position j and increment j
if (i != j) {
inttemp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j++;
}
}
}
}