forked from vengateshm/Java-Coding-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayPrograms.java
More file actions
137 lines (112 loc) · 3.23 KB
/
ArrayPrograms.java
File metadata and controls
137 lines (112 loc) · 3.23 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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package arrayPrograms;
import java.util.HashSet;
import java.util.Set;
public class ArrayPrograms {
// Find leaders in an array
public static void findLeaders(int[] arr) {
if (arr.length == 0) {
return;
}
int length = arr.length;
if (length == 1) {
System.out.print(arr[0]);
return;
}
int max = arr[length - 1];
System.out.print(max + " ");
for (int i = length - 2; i >= 0; i--) {
if (arr[i] > max) {
System.out.print(arr[i] + " ");
max = arr[i];
}
}
}
// Find intersection of two arrays
public static void findIntersection(int[] arr1, int[] arr2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int e : arr1) {
set1.add(e);
}
for (int e : arr2) {
set2.add(e);
}
set1.retainAll(set2);
System.out.println(set1);
}
// Find intersection of two arrays
public static void findIntersection1(int[] arr1, int[] arr2) {
Set<Integer> set1 = new HashSet<>();
for (int e : arr1) {
set1.add(e);
}
// Using contains
for (int e : arr2) {
if (set1.contains(e)) {
System.out.print(e + " ");
}
}
// Using add
/*for (int e : arr2) {
if (!set1.add(e)) {
System.out.print(e + " ");
}
}*/
}
public static String[] sortArrayAscending(String[] arr) {
int length = arr.length;
String temp;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (arr[i].compareToIgnoreCase(arr[j]) > 0) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
public static String[] sortArrayDescending(String[] arr) {
int length = arr.length;
String temp;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (arr[i].compareToIgnoreCase(arr[j]) < 0) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
public static int[] getOddNumbers(int[] arr) {
int oddNoCount = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0) {
oddNoCount++;
}
}
int[] result = new int[oddNoCount];
int resultIndex = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0) {
result[resultIndex] = arr[i];
resultIndex += 1;
}
}
return result;
}
public static int[] removeArrayElement(int[] arr, int element) {
int length = arr.length;
int[] newArr = new int[length - 1];
int newArrIndex = 0;
for (int j : arr) {
if (j != element) {
newArr[newArrIndex++] = j;
}
}
return newArr;
}
}