Sorting array contains some arrays in java - java

I have a array that contains arrays in it.
and I need to write a function that sort the little array on the big array( I mean the minimum sum of the little array is be the first on the index 0 and after the second on index1 and the maximum sum of the little array in in the end of the big aray =index bigArray.length-1
How can I sort an array that contains arrays in it?
i need to do that with no object or things like that. just regular and simple code.
enter image description here
public static int [][] sum (int [][] arr) {
int sum=0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
sum=sum+arr[i][j];
}

Since summing the inner array is a relatively time-consuming process, and the sum value is needed more than once when sorting, you should create an object to hold the array and the sum, e.g.
static class ArraySum implements Comparable<ArraySum> {
final int[] array;
final int sum;
ArraySum(int[] array) {
this.array = array;
this.sum = Arrays.stream(array).sum();
}
#Override
public int compareTo(ArraySum that) {
return Integer.compare(this.sum, that.sum);
}
}
Since it's Comparable, you can sort it directly, so with that in hand, you can easily sort the outer array using Java 8+ streams:
public static int[][] sort(int[][] arr) {
return Arrays.stream(arr).map(ArraySum::new).sorted()
.map(a -> a.array).toArray(int[][]::new);
}
That doesn't sort the input 2D array, but returns a new 2D array, i.e. a new outer array with the original inner arrays sorted.
Test
int[][] arr = { { 3, 5, 4 }, { 4, 3, 1, 2 }, { 5, 6 } };
int[][] arr2 = sort(arr);
System.out.println(Arrays.deepToString(arr));
System.out.println(Arrays.deepToString(arr2));
Output
[[3, 5, 4], [4, 3, 1, 2], [5, 6]]
[[4, 3, 1, 2], [5, 6], [3, 5, 4]]
// 10 11 12 sum
As you can see, the original 2D array is unmodified, and the new array is sorted by the sum of the inner arrays.

I don't think this works perfectly, but it should definitely get you close. I believe this is a buble sort technique.
public static int [][] sum (int [][] arr) {
//start at first array
for (int i = 0; i < arr.length - 1; i++) {
//sum of first array
int sum1 = 0;
for (int j = 0; j < arr[i].length; j++){
sum1 += arr[i][j];
}
//compare to each of the arrays after
for (int k = i+1; k < arr.length; k++) {
int sum2 = 0;
for (int l = 0; l < arr[k].length; j++){
sum2 += arr[k][l];
}
//if second array is smaller, swap
if (sum2 < sum1){
//might need to change this part to do complete copy
temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
}
return arr
}

Related

How can I find duplicate integers between two arrays and copy them into a new array?

To begin, I am doing this using only arrays (no hash maps or array lists).
I am trying to create a method, project, which inputs two integer arrays with different sizes.
I am trying to compare them in a way to get the following output: projecting [1, 3, 5, 3] to [2, 1, 6, 3, 1, 4, 5, 3] results in: [1, 3, 1, 5, 3].
However, projecting [2, 1, 6, 3, 1, 4, 5, 3] to [1, 3, 5, 3] results in: [1, 3, 5, 3].
I believe the nested for loop might be wrong as it is iterating through the first indices for the first array all the way through the second array, then going to the next.
I'm getting an ArrayIndexOutOfBoundsException for the starred line (tempArray[i] == arr1[i], I know it shouldn't be tempArray[i] but not sure what exactly to put).
I'm not sure how to compare them in a way to produce the line above, as it needs to be "in order". What could be the best way to accomplish this?
I attempted the following code:
public int[] project(int[] arr1, int[] arr2) {
int counter = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
counter++;
}
}
}
int[] tempArray = new int[counter];
for(int i = 0 ; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if(arr1[i] == arr2[j]) {
tempArray[i] = arr1[i]; // UNDERLINED
}
}
}
}
Edit
The ArrayIndexOutOfBounds error is gone, but now my return statement is: projecting [1, 3, 5] to [2, 1, 6, 3, 1, 4, 5, 3] results in: [1, 3, 5, 0, 0], when it needs to be: projecting [1, 3, 5] to [2, 1, 6, 3, 1, 4, 5, 3] results in: [1, 3, 1, 5, 3].
Any idea what is causing this issue?
I think you have a typo in your first for loop
change this to later
arr1[i] == arr2[i]
to
arr1[i] == arr2[j]
Regarding overlapping issues in the projection array, you need to maintain different value as your index rather than i or j which is used by arr1 and arr2 respectively
int[] tempArray = new int[counter];
int index = 0;
for(int i=0 ; i < arr1.length; i++) {
for (int j=0; j < arr2.length; j++) {
if(arr1[i] == arr2[j]) {
tempArray[index++] = arr1[i];
}
}
}
For the values which you are expecting you should loop through arr2 first
for(int j=0 ; j < arr2.length; j++) {
for (int i=0; i < arr1.length; i++) {
if(arr1[i] == arr2[j]) {
tempArray[index++] = arr1[i];
}
}
}
If the contents of array are not hardcoded and you dont know the order in which you want to pass, you can make use of length
int[] ans;
if(a.length < b.length) {
ans = project(a, b);
} else {
ans = project(b, a);
}
Output:
[1, 3, 1, 5, 3]
You currently have index variables (i, j) tracking the indexes of each input array as you loop through them, but you also need to keep track of the write head of the result array. Initialize, say int k = 0 before the outer for loop, then set the value like this: tempArray[k++] = array1[i];.
You can forgo the first loop If you are OK with performing a single array copy. Initialize an array as long as the second input array (since there can never be more duplicated elements than existing elements) as the tempArray. Then if you want it to fit exactly, initialize the final array to the exact length k and use System#arrayCopy.
this will probably solve your problem
public int[] project(int[] arr1, int[] arr2) {
int counter = 0;
for (int i : arr2) {
if (Arrays.binarySearch(arr1, i) >= 0) {
counter++;
}
}
int[] arr4 = new int[counter];
int index = 0;
for (int i : arr2) {
if (Arrays.binarySearch(arr1, i) >= 0) {
arr4[index++] = i;
}
}
return arr4;
}
The nested iteration is expensive, so we want to avoid that. The first thing to do is sort the array we are projecting from so we can perform a binary search on it. Second, don't execute the nested iteration to determine the output array size. Create an array the size of the array we are projecting to since it can be no longer than that.
public int[] projection(int[] a, int[] b) {
int[] temp = new int[b.length];
int nextIndex = 0;
for (int x : b) {
if (contains(a, x)) {
temp[nextIndex++] = x;
}
}
return slice(temp, nextIndex);
}
private boolean contains(int[] array, int value) {
for (int element : array) {
if (element == value) {
return true;
}
}
return false;
}
private int[] slice(int[] src, int size) {
int[] slice = new int[size];
for (int index = 0 ; index < size ; ++index) {
slice[index] = src[index];
}
return slice;
}
For your second problem, I think, in your temporary array, you should be saving the values from arr2[j] instead of arr1[i].
Also, you need a different counter (set to 0 initially and incremented in the loop) for setting the values in tempArray[counter].
What I mean exactly is:
int counter = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
tempArray[counter] = arr2[j];
counter++;
}
}
}

Sort a 2d array by the length of subarrays

I want to complete the following task:
You get an array of arrays.
If you sort the arrays by their length, you will see, that their length-values are consecutive. But one array is missing! You have to write a method, that return the length of the missing array.
public static int getLengthOfMissingArray(Object[][] arrayOfArrays) {
if (arrayOfArrays.length == 0) { //array empty
return 0;
}
for (int i = 0; i < arrayOfArrays.length; i++) {
//array in the array empty
if (arrayOfArrays[i].length == 0) {
return 0;
}
if (arrayOfArrays[i].length != arrayOfArrays[i + 1].length - 1) {
return arrayOfArrays[i].length + 1;
}
}
return 0;
}
This works for sorted arrays. So I just need a way to order them by their length.
Is there away to sort a 2D array by the (ascending) length of its subarrays?
For example: [[1,2], [1,5,7],[4]] -> [[4], [1,2], [1,5,7]]
Arrays.sort(arr) doesn't work and I get:
Ljava.lang.Object; cannot be cast to java.lang.Comparable
Use this method:
public static int[][] sort(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[j].length < arr[i].length) {
// If the length of the array in j less than the
// length of the array in i, replace between them
int[] temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
You can use Arrays.sort(T[],Comparator) method:
Object[][] arr = {{1, 2}, {1, 5, 7}, {4}};
Arrays.sort(arr, Comparator.comparing(subArr -> subArr.length));
System.out.println(Arrays.deepToString(arr));
// [[4], [1, 2], [1, 5, 7]]
See also: Sort a 2d array by the first column, and then by the second one

Checking if two int arrays have duplicate elements, and extract one of the duplicate elements from them

I'm trying to write a method, union(), that will return an int array, and it takes two int array parameters and check if they are sets, or in other words have duplicates between them. I wrote another method, isSet(), it takes one array argument and check if the array is a set. The problem is I want to check if the two arrays in the union method have duplicates between them, if they do, I want to extract one of the duplicates and put it in the unionArray[] int array. This is what I tried so far.
public int[] union(int[] array1, int[] array2){
int count = 0;
if (isSet(array1) && isSet(array2)){
for (int i = 0; i < array1.length; i++){
for (int j = 0; j < array2.length; j++){
if (array1[i] == array2[j]){
System.out.println(array2[j]);
count ++;
}
}
}
}
int[] array3 = new int[array2.length - count];
int[] unionArray = new int[array1.length + array3.length];
int elementOfUnion = 0;
for (int i = 0; i< array1.length; i++){
unionArray[i] = array1[i];
elementOfUnion = i + 1 ;
}
int index = 0;
for (int i = elementOfUnion; i < unionArray.length; i++){
unionArray[i] = array3[index];
index++;
}
return unionArray;
}
public boolean isSet(int[] array){
boolean duplicates = true;
for (int i = 0; i < array.length; i++){
for(int n = i+1; n < array.length; n++){
if (array[i] == array[n])
duplicates = false;
}
}
return duplicates;
}
What I was trying to do is to use all of array1 elements in the unionArray, check if array2 has any duplicates with array1, and then move all the non-duplicate elements from array2 to a new array3, and concatenate array3 to unionArray.
It will be much easier to do it with Collection API or Stream API. However, you have mentioned that you want to do it purely using arrays and without importing any class, it will require a few lengthy (although simple) processing units. The most important theories that drive the logic is how (given below) a union is calculated:
n(A U B) = n(A) + n(B) - n(A ∩ B)
and
n(Only A) = n(A) - n(A ∩ B)
n(Only B) = n(B) - n(A ∩ B)
A high-level summary of this solution is depicted with the following diagram:
Rest of the logic has been very clearly mentioned through comments in the code itself.
public class Main {
public static void main(String[] args) {
// Test
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 3, 4, 5, 6 }));
display(union(new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 1, 2, 3, 4 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 3, 4 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 4, 5 }));
display(union(new int[] { 1, 2, 3, 4, 5, 6 }, new int[] { 7, 8 }));
}
public static int[] union(int[] array1, int[] array2) {
// Create an array of the length equal to that of the smaller of the two array
// parameters
int[] intersection = new int[array1.length <= array2.length ? array1.length : array2.length];
int count = 0;
// Put the duplicate elements into intersection[]
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
intersection[count++] = array1[i];
}
}
}
// Create int []union of the length as per the n(A U B) = n(A) + n(B) - n(A ∩ B)
int[] union = new int[array1.length + array2.length - count];
// Copy array1[] minus intersection[] into union[]
int lastIndex = copySourceOnly(array1, intersection, union, count, 0);
// Copy array2[] minus intersection[] into union[]
lastIndex = copySourceOnly(array2, intersection, union, count, lastIndex);
// Copy intersection[] into union[]
for (int i = 0; i < count; i++) {
union[lastIndex + i] = intersection[i];
}
return union;
}
static int copySourceOnly(int[] source, int[] exclude, int[] target, int count, int startWith) {
int j, lastIndex = startWith;
for (int i = 0; i < source.length; i++) {
// Check if source[i] is present in intersection[]
for (j = 0; j < count; j++) {
if (source[i] == exclude[j]) {
break;
}
}
// If j has reached count, it means `break;` was not executed i.e. source[i] is
// not present in intersection[]
if (j == count) {
target[lastIndex++] = source[i];
}
}
return lastIndex;
}
static void display(int arr[]) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(i < arr.length - 1 ? arr[i] + ", " : arr[i]);
}
System.out.println("]");
}
}
Output:
[1, 2, 5, 6, 3, 4]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 5, 4]
[1, 2, 3, 4, 5, 6, 7, 8]
Using Java's streams could make this quite simpler:
public int[] union(int[] array1, int[] array2) {
return Stream.of(array1, array2).flatMapToInt(Arrays::stream).distinct().toArray();
}
Even with all the restrictions of only using arrays, you can simplify your code a lot. No need to check for sets. Just :
allocate an array to store all elements of the union (i.e., int[] tmp_union ), which at worst will be all elements from both arrays array1 and array2.
iterate over the elements of array1 and compared them against the elements from tmp_union array, add them into the tmp_union array only if they were not yet added to that array.
Repeat 2) for the array2.
During this process keep track of the number of elements added to the tmp_union array so far (i.e., added_so_far). In the end, copy the elements from the tmp_union array into a new array (i.e., unionArray) with space allocated just for the union elements. The code would look something like:
public static int[] union(int[] array1, int[] array2){
int[] tmp_union = new int[array1.length + array2.length];
int added_so_far = add_unique(array1, tmp_union, 0);
added_so_far = add_unique(array2, tmp_union, added_so_far);
return copyArray(tmp_union, added_so_far);
}
private static int[] copyArray(int[] ori, int size) {
int[] dest = new int[size];
for(int i = 0; i < size; i++)
dest[i] = ori[i];
return dest;
}
private static int add_unique(int[] array, int[] union, int added_so_far) {
for (int element : array)
if (!is_present(union, added_so_far, element))
union[added_so_far++] = element;
return added_so_far;
}
private static boolean is_present(int[] union, int added_so_far, int element) {
for (int z = 0; z < added_so_far; z++)
if (element == union[z])
return true;
return false;
}

Sorting from one array into another, Java

My goal is to move the elements in the ar[] array into the sorted[] array and sort them from least to greatest. I'm having trouble with that part though because my loop is supposed to find the smallest element in the array and then replace the element with a large number. I think I have most of the code down but when I run the program, every element in the sorted[] array is 2. What am I doing wrong here?
public class Lab1
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[ar.length];
int smallest = ar[0];
int smallestindex = 0;
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n];
smallestindex = n;
}
}
sorted[i] = smallest;
ar[i] = 1000000;
}
// print sorted array:
for (int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
What about something like this?
Short and sweet:
import java.util.Arrays;
public class Lab1
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = ar.clone();
Arrays.sort(sorted);
System.out.println("Original array: " + Arrays.toString(ar));
System.out.println("Sorted array: " + Arrays.toString(sorted));
}
}
Output:
Original array: [7, 5, 2, 8, 4, 9, 6]
Sorted array: [2, 4, 5, 6, 7, 8, 9]
I don't have my pc now but I think the problem is that once you set the variable smallest with 2 the first time, it remains 2 forever and there is no other number smaller. So I think you are executing the internal if just once and the value is always 2.
Edit. I think that moving the smallest inizialization below the fist for should work.
You didn't do any action when this condition is not true.
if (ar[n] < smallest)
So just smallest element can pass this check and goes on new array.
Also you can sort your array in better shape like this
List<Integer> ar = Arrays.as list ( *your numbers here*);
Collections.sort(ar):
oops, there is a problem inside your loop,
which copy the smallest in ar[] into sorted[], which is 2,
so you are getting 2 in every element inside sorted[].
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n]; <----YOU ALWAYS GET 2 HERE
smallestindex = n;
}
}
sorted[i] = smallest; <---- AND SET 2 TO YOUR sorted[] HERE
ar[i] = 1000000;
}
I don't know if you want a solution or solve it yourself since your question is asking what's wrong, but here it is
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n];
smallestindex = n;
ar[n] = 1000000; <----CHANGE THE SMALLEST ITEM HERE RATHER THAN OUTSIDE
}
}
sorted[i] = smallest;
}
btw, to make a sorted copy in a easier way:
Firsy make a copy:
int[] sorted = ar.clone();
Then, sort it using Java Util:
Arrays.sort(sorted);
Just 2 lines you get what you want.
I just can't understand, why do we require this, like sorting into another array. You can sort within the array using Arrays.sort() method, or if you want to sort in a different array, you can take following steps:
Copy the array to new array.
Sort the new array and then sort.
If you still want to go with your implementation, then I have refactored your code. Now your code works fine and looks like:
public class Prog1 {
public static void main(String[] args) {
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[ar.length];
int smallest = ar[0];
int smallestindex = 0;
for (int i = 0; i < ar.length; i++) {
for (int n = 0; n < ar.length; n++) {
if (ar[n] < smallest) {
smallest = ar[n];
smallestindex = n;
}
}
sorted[i] = smallest;
//Your mistake was here.
ar[smallestindex] = 1000000;
smallest=ar[0];
smallestindex=0;
}
// print sorted array:
for (int i = 0; i < sorted.length; i++) {
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
Your mistake was that you were not reassigning 'smallest' variable. As it was pointing to the smallest element of array so it doesn't get updated in next run because no element in array is less than this variable. Hope you get it. If any questions, you still have, please ask.
Because each time you crush old value (big value) and you don't save it for shifting
smallest = ar[n]; smallestindex = n; You need to add another variable to change values between cells ,or use arraylist for easy way.
int ar[] = {7, 5, 2, 8, 4, 9, 6};
int sorted[] = new int[ar.length];
int smallest = ar[0];
for (int i = 0; i < ar.length ; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) {
smallest = ar[j]; //save small value
ar[j] = ar[i];//transaction between two comparables cells
ar[i] = smallest;//set small value as first
}
sorted[i]=ar[i]; //set first small value
}
}
// print sorted array:
for (int i = 0; i < sorted.length; i++) {
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
It seems you want to sort by using an algorithm called 'Selection Sort', but your code is a poorly implement.
You can learn from this brother's question and check the answers below that:
Selection Sort Example

Java - Merge Two Arrays without Duplicates (No libraries allowed)

Need assistance with programming issue.
Must be in Java. Cannot use any libraries (Arraylist, etc.).
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0}
int[] b = {0, 2, 11, 12, 5, 6, 8}
Have to create an object referencing these two arrays in a method that merges them together, removes duplicates, and sorts them.
Here's my sort so far. Having difficulty combining two arrays and removing duplicates though.
int lastPos;
int index;
int temp;
for(lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for(index = 0; index <= lastPos - 1; index++) {
if(a[index] > a[index+1]) {
temp = a[index];
a[index] = a[index+1];
a[index+1] = temp;
}
}
}
a method that merges them together, removes duplicates, and sorts them.
I suggest you break this down into helper methods (and slightly tweak the order of operations). Step 1, merge the two arrays. Something like,
static int[] mergeArrays(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
c[a.length + i] = b[i];
}
return c;
}
Step 2, sort the new array (your existing sort algorithm is fine). Like,
static void sortArray(int[] a) {
for (int lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for (int index = 0; index <= lastPos - 1; index++) {
if (a[index] > a[index + 1]) {
int temp = a[index];
a[index] = a[index + 1];
a[index + 1] = temp;
}
}
}
}
Finally, remove duplicates. Step 3a, count unique values. Assume they're unique, and decrement by counting adjacent (and equal) values. Like,
static int countUniqueValues(int[] c) {
int unique = c.length;
for (int i = 0; i < c.length; i++) {
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
unique--;
}
}
return unique;
}
Then step 3b, take the unique count and build your result with the previous methods. Like,
public static int[] mergeDedupSort(int[] a, int[] b) {
int[] c = mergeArrays(a, b);
sortArray(c);
int unique = countUniqueValues(c);
int[] d = new int[unique];
int p = 0;
for (int i = 0; i < c.length; i++) {
d[p++] = c[i];
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
}
}
return d;
}
Then you can test it with your arrays like
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 8, 5, 7, 9, 6, 0 };
int[] b = { 0, 2, 11, 12, 5, 6, 8 };
int[] c = mergeDedupSort(a, b);
System.out.println(Arrays.toString(c));
}
And I get
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12]
Merge Two Arrays without Duplicates and Sort it (No libraries used).
Using an object.
public class MergeRemoveDupSort {
public int[] mergeRemoveDupSortIt(int[] a, int[] b) {
int [] c = mergeIt(a,b);
int [] d = removeIt(c);
int [] e = sortIt(d);
return e;
}
private int[] mergeIt(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int k=0;
for (int n : a) c[k++]=n;
for (int n : b) c[k++]=n;
return c;
}
private int[] removeIt(int[] c) {
int len=c.length;
for (int i=0;i<len-1;i++)
for (int j=i+1;j<len;j++)
if (c[i] == c[j]) {
for (int k=j;k<len-1;k++)
c[k]=c[k+1];
--len;
}
int [] r = new int[len];
for (int i=0;i<r.length;i++)
r[i]=c[i];
return r;
}
private int[] sortIt(int[] a) {
for(int index=0; index<a.length-1; index++)
for(int i=index+1; i<a.length; i++)
if(a[index] > a[i]){
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
return a;
}
public void printIt(int[] a) {
System.out.print("[");
for (int i=0;i<a.length;i++){
System.out.print(a[i]);
if (i!=a.length-1) System.out.print(",");
else System.out.print("]");
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
MergeRemoveDupSort array = new MergeRemoveDupSort();
int [] r = array.mergeRemoveDupSortIt(a, b);
array.printIt(r);
}
}
You should use IntStream like this.
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] merged = IntStream
.concat(IntStream.of(a), IntStream.of(b))
.distinct()
.sorted()
.toArray();
System.out.println(Arrays.toString(merged));
Assuming that array a and array b are sorted, the following code will merge them into a third array merged_array without duplicates :
public static int[] get_merged_array(int[] a, int[] b, int a_size, int b_size)
{
int[] merged_array = new int[a_size + b_size];
int i = 0 , j = 0, x = -1;
for(; i < a_size && j < b_size;)
{
if(a[i] <= b[j])
{
merged_array[++x] = a[i];
++i;
}
else
{
if(merged_array[x] != b[j])
{
merged_array[++x] = b[j]; // avoid duplicates
}
++j;
}
}
--i; --j;
while(++i < a_size)
{
merged_array[++x] = a[i];
}
while(++j < b_size)
{
merged_array[++x] = b[j];
}
return merged_array;
}
Hope this may help, all the best :)
try{
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] c = new int[a.length+b.length];
int[] final = new int[a.length+b.length];
int i = 0;
for(int j : final){
final[i++] = -1;
}
i = 0;
for(int j : a){
c[i++] = j;
}
for(int j : b){
c[i++] = j;
}
boolean check = false;
for(int j = 0,k = 0; j < c.length; j++){
for(int l : fin){
if( l == c[j] )
check = true;
}
if(!check){
final[k++] = c[j];
} else check = false;
}
} catch(Exception ex){
ex.printStackTrace();
}
I prefer you to use Hashset for this cause it never allow duplicates
and there is another method in java 8 for arraylist to remove duplicates
after copying all elements to c follow this code
List<Integer> d = array.asList(c);
List<Integer> final = d.Stream().distinct().collect(Collectors.toList());
final.forEach(System.out::println());
This code is lot much better than previous one and you can again transform final to array like this
int array[] = new int[final.size()];
for(int j =0;j<final.size();j++){
array[j] = final.get(j);
}
Hope my work will be helpful .
Let me restate your question.
You want a program that takes two arbitrary arrays, merges them removing any duplicates, and sorts the result.
First of all, if you have access to any data structure, there are much better ways of doing this. Ideally, you would use something like a TreeSet.
However, assuming all you have access to is arrays, your options are much more limited. I'm going to go ahead and assume that each of the two arrays initially has no duplicates.
Let's assume the first array is of length m and the second array is of length n.
int[] array1; // length m
int[] array2; // length n
First, let's sort both arrays.
Arrays.sort(array1);
Arrays.sort(array2);
This assumes you have access to the Arrays class which is part of the standard Java Collections Framework. If not, any reasonable merge implementation (like MergeSort) will do the trick.
The sorts will take O(n log n + m log m) with most good sort implementations.
Next, let's merge the two sorted arrays. First, we need to allocate a new array big enough to hold all the elements.
int[] array3 = new int[size];
Now, we will need to insert the elements of array1 and array2 in order, taking care not to insert any duplicates.
int index=0, next=0, i=0, j=0;
int last = Integer.MAX_INT;
while(i < m || j < n) {
if(i == m)
next = array2[j++];
else if(j == n)
next = array1[i++];
else if(array1[i] <= array2[j])
next = array1[i++];
else
next = array2[j++];
if(last == next)
continue;
array3[index++] = next;
}
Now, you have your array. Just one problem - it could have invalid elements at the end. One last copy should take care of it...
int[] result = Arrays.copyOf(array3, index + 1);
The inserts and the final copy will take O(n + m), so the overall efficiency of the algorithm should be O(n log n + m log n).

Categories