Motivation: In Java, check if Two Arrays are Equal or not Equal.
a={1,2,3,4,5,6}
b={2,3,1,4,5,4,4}
Time complexity: $O(n^2)$ (because of the bubble sort algorithm)
- Version 1: 1 process. double-nested loop statement.
- Version 2: 2 processes. 1) bubble sort algorithm: $O(n^2)$, 2) single-nested loop statement O(n)
- Version 3: 1 process. 1) Arrays.equals(a, b): $O(n^2)$ (still $n^2$)
- Version 4: 2 processes. 1) check lengths of arrays, 2) sort arrays, 3) compare elements of arrays. Still $O(n^2)$ because of sorting arrays.
Java codes
public static void main(String[] args) {
int a[] = {1,2,3,4,5,6};
int b[] = {2,3,1,4,5,4,4};
boolean result = true;
// version 1
// determine whether two arrays are equal, by comparing elements one-by-one: version 1
// this is theta(n^2) algorithm
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i]!=b[j]) {
result = false;
}
}
}
// Display result (true or false)
System.out.print("Version 1: result using double nested loop statements (O(n^2)): " );
System.out.println(result);
// sort arrays: version 2
// this is theta(n^2) algorithm
// sort array a
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - 1; j++) {
if (a[j] > a[j+1]) {
// swap
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
// sort array b
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b.length - 1; j++) {
if (b[j] > b[j+1]) {
// swap
int temp = b[j];
b[j] = b[j+1];
b[j+1] = temp;
}
}
}
// print array a
System.out.print("Sorted array a: ");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]);
}
// make a new line
System.out.println();
// print array b
System.out.print("Sorted array b: ");
for (int i = 0; i < b.length; i++) {
System.out.print(b[i]);
}
// determine whether two arrays are equal, by comparing elements one-by-one: version 2
// this is theta(n) algorithm, given that arrays are sorted
int i = 0;
int j = 0;
while (i < a.length && j < b.length) {
// elements are equal
if (a[i] == b[j]) {
i = i + 1;
j = j + 1;
}
else {
result = false;
break;
}
result = true;
}
System.out.println();
System.out.println("Version 2: result using 1) sorted Arrays (O(n^2)), 2) a single nested loop (O(n)). 3) still final time complexity is O(n^2) : ");
System.out.print(result); // false if output is 1, true if 0.
System.out.println();
// Version 3:
boolean result2 = Arrays.equals(a, b);
System.out.println("Result using Arrays.equals(a,b): " + result2);
// Version 4:
boolean result3 = true;
int c[] = {2,3,1,4,5,4,4};
if (a.length != c.length) {
result = false;
} else {
// Sort arrays
Arrays.sort(a);
Arrays.sort(c);
// Check if arrays are equal
for (int index = 0; index < a.length; index++) {
if (a[index] != c[index]) {
result = false;
break;
}
}
}
System.out.println("Result using Arrays.sort: " + result);
} // end of main
Comments
Post a Comment