Generic MergeSort with Permutation Array - java

I have code for a MergeSort of generic arrays. The only problem is, that I want the output to be with the index instead of the actual int, float or whatever. Do you guys have any idea on how to do that?
Here is the code I have so far:
class MergeSortGeneric<T extends Comparable<? super T>> {
public static void main(String[] args)
{
// example using Strings
String[] arrayOfStrings = {"Andree", "Leana", "Faviola", "Loyce", "Quincy",
"Milo", "Jamila", "Toccara", "Nelda", "Blair", "Ernestine", "Chara", "Kareen", "Monty", "Rene",
"Cami", "Winifred", "Tara", "Demetrice", "Azucena"};
MergeSortGeneric<String> stringSorter = new MergeSortGeneric<>();
stringSorter.mergeSort(arrayOfStrings, 0, arrayOfStrings.length - 1);
System.out.println(java.util.Arrays.toString(arrayOfStrings));
// example using Doubles
Double[] arrayOfDoubles = {0.35, 0.02, 0.36, 0.82, 0.27, 0.49, 0.41, 0.17, 0.30,
0.89, 0.37, 0.66, 0.82, 0.17, 0.20, 0.96, 0.18, 0.25, 0.37, 0.52};
MergeSortGeneric<Double> doubleSorter = new MergeSortGeneric<>();
doubleSorter.mergeSort(arrayOfDoubles, 0, arrayOfDoubles.length - 1);
System.out.println(java.util.Arrays.toString(arrayOfDoubles));
}
// main function that sorts array[start..end] using merge()
void mergeSort(T[] array, int start, int end)
{
// base case
if (start < end)
{
// find the middle point
int middle = (start + end) / 2;
mergeSort(array, start, middle); // sort first half
mergeSort(array, middle + 1, end); // sort second half
// merge the sorted halves
merge(array, start, middle, end);
}
}
// merges two subarrays of array[].
void merge(T[] array, int start, int middle, int end)
{
T[] leftArray = (T[]) new Comparable[middle - start + 1];
T[] rightArray = (T[]) new Comparable[end - middle];
// fill in left array
for (int i = 0; i < leftArray.length; ++i)
leftArray[i] = array[start + i];
// fill in right array
for (int i = 0; i < rightArray.length; ++i)
rightArray[i] = array[middle + 1 + i];
/* Merge the temp arrays */
// initial indexes of first and second subarrays
int leftIndex = 0, rightIndex = 0;
// the index we will start at when adding the subarrays back into the main array
int currentIndex = start;
// compare each index of the subarrays adding the lowest value to the currentIndex
while (leftIndex < leftArray.length && rightIndex < rightArray.length)
{
if (leftArray[leftIndex].compareTo(rightArray[rightIndex]) <= 0)
{
array[currentIndex] = leftArray[leftIndex];
leftIndex++;
}
else
{
array[currentIndex] = rightArray[rightIndex];
rightIndex++;
}
currentIndex++;
}
// copy remaining elements of leftArray[] if any
while (leftIndex < leftArray.length) array[currentIndex++] = leftArray[leftIndex++];
// copy remaining elements of rightArray[] if any
while (rightIndex < rightArray.length) array[currentIndex++] = rightArray[rightIndex++];
}
}
thank you guys for any tips. Thats the task by the way:
Implement the Merge-Sort algorithm. The algorithm sorts a java.util.list
of any elements. Therefore the class must be generic. For sorting it gets a
matching comparator.
var data = Arrays.asList(23, 42, 11, 1, 12);
var mergeSort = new MergeSort<Integer>();
mergeSort.setup(data, (i1, i2) -> i1 - i2);
However, the element positions in the input list are not changed. Instead, the
specifies the sorting by a permutation array. The array has as many in-elements as
the input data list has elements. Each τ element specifies the index of the corresponding input element after sorting. Also internally you use only permutation arrays and no
further lists of input elements.

The easiest way without modifying the merge algorithm you be:
Create a copy of the arrays to be sorted;
Sort the arrays;
Compare the copy and the sorted array and figure it out the index.
For example:
String[] arrayOfStrings = {...};
List<String> copyArrayOfStrings = Arrays.stream(arrayOfStrings).collect(Collectors.toList());
...
stringSorter.mergeSort(arrayOfStrings, 0, arrayOfStrings.length - 1);
...
List<Integer> index = Arrays.stream(arrayOfStrings).map(copyArrayOfStrings::indexOf).collect(Collectors.toList());
System.out.println(java.util.Arrays.toString(index.toArray()));
If for some strange reason you can only use arrays, and basic operators, the aforementioned logic still holds true:
the copy:
String[] copyArrayOfStrings = new String[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
copyArrayOfStrings[i] = arrayOfStrings[i];
}
the sorting:
stringSorter.mergeSort(arrayOfStrings, 0, arrayOfStrings.length - 1);
getting the indexes:
Integer[] index = new Integer[copyArrayOfStrings.length];
int index_pos = 0;
for(String s : arrayOfStrings) {
for (int i = 0; i < copyArrayOfStrings.length; i++) {
if(copyArrayOfStrings[i].equals(s)){
index[index_pos++] = i;
break;
}
}
}
System.out.println(java.util.Arrays.toString(index));

You can use a lambda compare, if the indexes are Integer types as opposed to native ints. Only the array of indices needs to be Integer type, the array of values can be primitive type.
package x;
import java.util.Arrays;
public class x {
public static void main(String[] args) {
int[] A = {3, 1, 2, 0};
Integer[] I = {0, 1, 2, 3};
Arrays.sort(I, (i, j) -> A[i]-A[j]);
for (Integer i : I) {
System.out.println(A[i]);
}
}
}

you can create a class like below (note it is pseudo code)
import java.util.Arrays;
public class SomeClass {
public static void main(String[] args) {
double[] doubleArray = new double[] {2.3, 3.4, 1.2, 0.3, 4.3};
ObjectWithIndex[] objectWithIndexAr = new ObjectWithIndex[doubleArray.length];
for (int i = 0; i < doubleArray.length; i++) {
objectWithIndexAr[i] = new ObjectWithIndex(i, doubleArray[i]);
}
Arrays.sort(objectWithIndexAr);
for ( ObjectWithIndex obj : objectWithIndexAr) {
System.out.println("index: " + obj.index + " value: " + obj.actualObject);
}
}
}
class ObjectWithIndex implements Comparable<ObjectWithIndex> {
int index;
Comparable actualObject;
public ObjectWithIndex(int index, Comparable object) {
this.index = index;
this.actualObject = object;
}
#Override
public int compareTo(ObjectWithIndex o) {
return this.actualObject.compareTo(o.actualObject);
}
}
you can create array of this object using your input array of Double, Integer (whatever implements Comparable) and sort the new array of ObjectWithIndex.
once sorted, you can print the index (which will have original index from your input)

Related

Rearrange an array in minimum and maximum java

Given an array of ints, I want to rearrange it alternately i.e. first element should be minimum, second should be maximum, third second-minimum, fourth second-maximum and so on...
I'm completely lost here...
Another method that doesn't require the space of three separate arrays but isn't as complex as reordering in place would be to sort the original array and then create a single new array. Then start iterating with a pointer to the current i-th index of the new array and pointers starting at the 0-th index and the last index of the sorted array.
public class Foo {
public static void main(String[] args) {
// Take your original array
int[] arr = { 1, 4, 5, 10, 6, 8, 3, 9 };
// Use the Arrays sort method to sort it into ascending order (note this mutates the array instance)
Arrays.sort(arr);
// Create a new array of the same length
int[] minMaxSorted = new int[arr.length];
// Iterate through the array (from the left and right at the same time)
for (int i = 0, min = 0, max = arr.length - 1; i < arr.length; i += 2, min++, max--) {
// the next minimum goes into minMaxSorted[i]
minMaxSorted[i] = arr[min];
// the next maximum goes into minMaxSorted[i + 1] ... but
// guard against index out of bounds for odd number arrays
if (i + 1 < minMaxSorted.length) {
minMaxSorted[i + 1] = arr[max];
}
}
System.out.println(Arrays.toString(minMaxSorted));
}
}
Hint:
Create two new arrays, 1st is sorted in assenting order and other is in descending order. Than select 1st element from 2nd array and 1st element from 1st array, repeat this selection until you reach half of both 1st and second array. and you will get your desired array.
Hope this will help you.
The approach in #Kaushal28's answer is the best approach for a beginner. It requires more space (2 extra copies of the array) but it is easy to understand and code.
An advanced programmer might consider sorting the array once, and then rearranging the elements. It should work, but the logic is complicated.
Hint: have you ever played "Clock Patience"?
This solution is based on Aaron Davis solution. I tried to make the looping easier to follow:
public class AltSort {
//list of array elements that were sorted
static Set<Integer> indexSorted = new HashSet<Integer>();
public static void main (String[] args) throws java.lang.Exception
{
//test case
int[] array = new int[]{7,22,4,67,5,11,-9,23,48, 3, 73, 1, 10};
System.out.println(Arrays.toString(altSort(array)));
//test case
array = new int[]{ 1, 4, 5, 10, 6, 8, 3, 9 };
System.out.println(Arrays.toString(altSort(array)));
}
private static int[] altSort(int[] array) {
if((array == null) || (array.length == 0)) {
System.err.println("Empty or null array can not be sorted.");
}
Arrays.sort(array);
//returned array
int[] sortedArray = new int[array.length];
int firstIndex = 0, lastIndex = array.length-1;
for (int i = 0; i < array.length; i++) {
if((i%2) == 0) { //even indices
sortedArray[i] = array[firstIndex++];
}
else {
sortedArray[i] = array[lastIndex --];
}
}
return sortedArray;
}
}
Here is another alternative: monitor the indices that have been sorted, and search the rest for the next min / max:
import java.util.Arrays;
import java.util.Set;
/**
* Demonstrates an option for sorting an int[] array as requested,
* by keeping a list of the array indices that has been sorted, and searching
* for the next min / max.
* This code is not optimal nor robust. It serves a demo for this option only.
*
*/
public class AltSort {
//list of array elements that were sorted
static Set<Integer> indexSorted ;
public static void main (String[] args) throws java.lang.Exception {
//test case
int[] array = new int[]{7,22,4,67,5,11,-9,23,48, 3, 73, 1, 10};
System.out.println(Arrays.toString(altSort2(array)));
//test case
array = new int[]{ 1, 4, 5, 10, 6, 8, 3, 9 };
System.out.println(Arrays.toString(altSort2(array)));
}
private static int[] altSort2(int[] array) {
if((array == null) || (array.length == 0)) {
System.err.println("Empty or null array can not be sorted.");
}
//returned array
int[] sortedArray = new int[array.length];
//flag indicating wether to look for min or max
boolean lookForMin = true;
int index = 0;
while(index < array.length) {
if(lookForMin) {
sortedArray[index] = lookForArrayMin(array);
}else {
sortedArray[index] = lookForArrayMax(array);
}
index++;
//alternate look for min / look for max
lookForMin = ! lookForMin;
}
return sortedArray;
}
private static int lookForArrayMin(int[] array) {
int minValue = Integer.MAX_VALUE;
int minValueIndex = 0;
for( int i =0; i< array.length; i++ ){
//if array[i] is min and was not sorted before, keep it as min
if( (array[i]< minValue) && ! indexSorted.contains(i) ) {
minValue = array[i]; //keep min
minValueIndex = i; //keep min index
}
}
//add the index to the list of sorted indices
indexSorted.add(minValueIndex);
return minValue;
}
private static int lookForArrayMax(int[] array) {
int maxValue = Integer.MIN_VALUE; //max value
int maxValueIndex = 0; //index of max value
for( int i =0; i< array.length; i++ ){
//if array[i] is max and was not sorted before, keep it as max
if( (array[i] > maxValue) && ! indexSorted.contains(i)) {
maxValue = array[i]; //keep max
maxValueIndex = i; //keep max index
}
}
//add the index to the list of sorted indices
indexSorted.add(maxValueIndex);
return maxValue;
}
}

Count pairs from an array whose sum is equal to a given number?

I just had an online coding interview and one of the questions asked there is for a given array of integers, find out the number of pairs whose summation is equal to a certain number (passed as parameter inside the method ). For example an array is given as,
int[] a = {3, 2, 1, 45, 27, 6, 78, 9, 0};
int k = 9; // given number
So, there will be 2 pairs (3, 6) and (9, 0) whose sum is equal to 9. It's good to mention that how the pairs are formed doesn't matter. The means (3,6) and (6,3) will be considered as same pair. I provided the following solution (in Java) and curious to know if I missed any edge cases?
public static int numberOfPairs(int[] a, int k ){
int len = a.length;
if (len == 0){
return -1;
}
Arrays.sort(a);
int count = 0, left = 0, right = len -1;
while( left < right ){
if ( a[left] + a[right] == k ){
count++;
if (a[left] == a[left+1] && left < len-1 ){
left++;
}
if ( a[right] == a[right-1] && right >1 ){
right-- ;
}
right--; // right-- or left++, otherwise, will get struck in the while loop
}
else if ( a[left] + a[right] < k ){
left++;
}
else {
right--;
}
}
return count;
}
Besides, can anyone propose any alternative solution of the problem ? Thanks.
Following solution will return the number of unique pairs
public static int numberOfPairs(Integer[] array, int sum) {
Set<Integer> set = new HashSet<>(Arrays.asList(array));
// this set will keep track of the unique pairs.
Set<String> uniquePairs = new HashSet<String>();
for (int i : array) {
int x = sum - i;
if (set.contains(x)) {
int[] y = new int[] { x, i };
Arrays.sort(y);
uniquePairs.add(Arrays.toString(y));
}
}
//System.out.println(uniquePairs.size());
return uniquePairs.size();
}
The time complexity will be O(n).
Hope this helps.
You can use the HashMap<K,V> where K: a[i] and V: k-a[i]
This may result in an incorrect answer if there are duplicates in an array.
Say for instances:
int a[] = {4, 4, 4, 4, 4, 4, 4, 4, 4}
where k = 8 or:
int a[] = {1, 3, 3, 3, 3, 1, 2, 1, 2}
where k = 4.
So in order to avoid that, we can have a List<List<Integer>> , which can check each pair and see if it is already in the list.
static int numberOfPairs(int[] a, int k)
{
List<List<Integer>> res = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for(int element:a)
{
List<Integer> list = new ArrayList<>();
if(map.containsKey(element))
{
list.add(element);
list.add(map.get(element));
if(!res.contains(list))
res.add(list);
}
else
map.put(k - element, element);
}
return res.size();
}
Your solution is overly complex, you can do this exercise in a much easier manner:
public static int numberOfPairs(int[] a, int k ){
int count=0;
List<Integer> dedup = new ArrayList<>(new HashSet<>(Arrays.asList(a)));
for (int x=0 ; x < dedup.size() ; x++ ){
for (int y=x+1 ; y < dedup.size() ; y++ ){
if (dedup.get(x)+dedup.get(y) == k)
count++;
}
}
return count;
}
The trick here is to have a loop starting after the first loop's index to not count the same values twice, and not compare it with your own index. Also, you can deduplicate the array to avoid duplicate pairs, since they don't matter.
You can also sort the list, then break the loop as soon as your sum goes above k, but that's optimization.
This code will give you count of the pairs that equals to given sum and as well as the pair of elements that equals to sum
private void pairofArrayElementsEqualstoGivenSum(int sum,Integer[] arr){
int count=0;
List numList = Arrays.asList(arr);
for (int i = 0; i < arr.length; i++) {
int num = sum - arr[i];
if (numList.contains(num)) {
count++;
System.out.println("" + arr[i] + " " + num + " = "+sum);
}
}
System.out.println("Total count of pairs "+count);
}
Given an array of integers and a target value, determine the number of pairs of array elements with a difference equal to a target value.
The function has the following parameters:
k: an integer, the target difference
arr: an array of integers
Using LINQ this is nice solution:
public static int CountNumberOfPairsWithDiff(int k, int[] arr)
{
var numbers = arr.Select((value) => new { value });
var pairs = from num1 in numbers
join num2 in numbers
on num1.value - k equals num2.value
select new[]
{
num1.value, // first number in the pair
num2.value, // second number in the pair
};
foreach (var pair in pairs)
{
Console.WriteLine("Pair found: " + pair[0] + ", " + pair[1]);
}
return pairs.Count();
}

Java, find intersection of two arrays

I have already read a few other stack overflow threads on this:
to find the intersection of two multisets in java
How do I get the intersection between two arrays as a new array?
public static int[] intersection (int [] x, int numELementsInX, int [] y, int numElementsInY) {
I am trying to examine two arrays as well as their number of elements (numElementsInX and numElementsInY), and return a new array which contains the common values of array x and y. Their intersection.
Example,if x is{1,3,5,7,9}and y is{9,3,9,4} then
intersection(x, 5, y, 4} should return {3, 9} or {9, 3}
I've read I need to use the LCS algorithm. Can anyone give me an example as to how to do this? Both the array and values in array are initialized and generated in another method, then passed into intersection.
Any help/clarification is appreciated.
EDIT CODE
for (int i=0; i<numElementsInX; i++){
for (int j=0; j<numElementsInY; j++){
if (x[j]==x[i]) { //how to push to new array?;
}
else{
}
}
}
The simplest solution would be to use sets, as long as you don't care that the elements in the result will have a different order, and that duplicates will be removed. The input arrays array1 and array2 are the Integer[] subarrays of the given int[] arrays corresponding to the number of elements that you intend to process:
Set<Integer> s1 = new HashSet<Integer>(Arrays.asList(array1));
Set<Integer> s2 = new HashSet<Integer>(Arrays.asList(array2));
s1.retainAll(s2);
Integer[] result = s1.toArray(new Integer[s1.size()]);
The above will return an Integer[], if needed it's simple to copy and convert its contents into an int[].
If you are fine with java-8, then the simplest solution I can think of is using streams and filter. An implementation is as follows:
public static int[] intersection(int[] a, int[] b) {
return Arrays.stream(a)
.distinct()
.filter(x -> Arrays.stream(b).anyMatch(y -> y == x))
.toArray();
}
General test
The answers provide several solutions, so I decided to figure out which one is the most effective.
Solutions
HashSet based by Óscar López
Stream based by Bilesh Ganguly
Foreach based by Ruchira Gayan Ranaweera
HashMap based by ikarayel
What we have
Two String arrays that contain 50% of the common elements.
Every element in each array is unique, so there are no duplicates
Testing code
public static void startTest(String name, Runnable test){
long start = System.nanoTime();
test.run();
long end = System.nanoTime();
System.out.println(name + ": " + (end - start) / 1000000. + " ms");
}
With use:
startTest("HashMap", () -> intersectHashMap(arr1, arr2));
startTest("HashSet", () -> intersectHashSet(arr1, arr2));
startTest("Foreach", () -> intersectForeach(arr1, arr2));
startTest("Stream ", () -> intersectStream(arr1, arr2));
Solutions code:
HashSet
public static String[] intersectHashSet(String[] arr1, String[] arr2){
HashSet<String> set = new HashSet<>(Arrays.asList(arr1));
set.retainAll(Arrays.asList(arr2));
return set.toArray(new String[0]);
}
Stream
public static String[] intersectStream(String[] arr1, String[] arr2){
return Arrays.stream(arr1)
.distinct()
.filter(x -> Arrays.asList(arr2).contains(x))
.toArray(String[]::new);
}
Foreach
public static String[] intersectForeach(String[] arr1, String[] arr2){
ArrayList<String> result = new ArrayList<>();
for(int i = 0; i < arr1.length; i++){
for(int r = 0; r < arr2.length; r++){
if(arr1[i].equals(arr2[r]))
result.add(arr1[i]);
}
}
return result.toArray(new String[0]);
}
HashMap
public static String[] intersectHashMap(String[] arr1, String[] arr2){
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < arr1.length; i++)
map.put(arr1[i], 1);
ArrayList<String> result = new ArrayList<>();
for(int i = 0; i < arr2.length; i++)
if(map.containsKey(arr2[i]))
result.add(arr2[i]);
return result.toArray(new String[0]);
}
Testing process
Let's see what happens if we give the methods an array of 20 elements:
HashMap: 0.105 ms
HashSet: 0.2185 ms
Foreach: 0.041 ms
Stream : 7.3629 ms
As we can see, the Foreach method does the best job. But the Stream method is almost 180 times slower.
Let's continue the test with 500 elements:
HashMap: 0.7147 ms
HashSet: 4.882 ms
Foreach: 7.8314 ms
Stream : 10.6681 ms
In this case, the results have changed dramatically. Now the most efficient is the HashMap method.
Next test with 10 000 elements:
HashMap: 4.875 ms
HashSet: 316.2864 ms
Foreach: 505.6547 ms
Stream : 292.6572 ms
The fastest is still the HashMap method. And the Foreach method has become quite slow.
Results
If there are < 50 elements, then it is best to use the Foreach method. He strongly breaks away in speed in this category.
In this case, the top of the best will look like this:
Foreach
HashMap
HashSet
Stream - Better not to use in this case
But if you need to process big data, then the best option would be use the HashMap based method.
So the top of the best look like this:
HashMap
HashSet
Stream
Foreach
With duplicate elements in array finding intersection.
int [] arr1 = {1,2,2,2,2,2,2,3,6,6,6,6,6,6,};
int [] arr2 = {7,5,3,6,6,2,2,3,6,6,6,6,6,6,6,6,};
Arrays.sort(arr1);
Arrays.sort(arr2);
ArrayList result = new ArrayList<>();
int i =0 ;
int j =0;
while(i< arr1.length && j<arr2.length){
if (arr1[i]>arr2[j]){
j++;
}else if (arr1[i]<arr2[j]){
i++;
}else {
result.add(arr1[i]);
i++;
j++;
}
}
System.out.println(result);
If you don't want to use other data structures such as a Set, then the basic idea is that you want to iterate through the elements of one of the arrays and for each value see if it appears in the other. How do you see whether it appears in the other array? Walk through the elements in the other array and for each one, see if its value is equal to the value you are looking for. I suspect that you will be best served by trying to work through this problem on your own beyond this point if your goal in taking the class is to learn to write Java well, but it you get stuck you might consider updating your question with the code that you have written so you can get more detailed feedback and pointers in the right direction.
Try this:
public static void main(String[] args) {
int[] arr1 = new int[]{1, 2, 3, 4, 5};
int[] arr2 = new int[]{3, 2, 5, 9, 11};
getIntersection(arr1, arr2);
}
public static Object[] getIntersection(int[] arr1, int[] arr2) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
list.add(arr1[i]);
}
}
}
return list.toArray();
}
You can find the intersection of two arrays with:
T[] result = Arrays.stream(a1)
.filter(new HashSet<>(Arrays.asList(a2))::contains)
.toArray(T[]::new);
where T should be substitutable by a reference type e.g. String, Integer, etc.
although the above may seem like it's creating a new set for each element, it's not the case at all. instead only one set instance is created.
The above code is equivalent to:
List<T> list = new ArrayList<>();
HashSet<T> container = new HashSet<>(Arrays.asList(a2));
for (T s : a1) {
if (container.contains(s)) list.add(s);
}
T[] result = list.toArray(new T[0]);
finding intersection includes duplicate using the hash map.
Output: 1 2 2 15 9 7 12
public static void main(String[] args) {
int[] arr1 = {1, 2, 2, 1, 5, 9, 15, 9, 7, 7, 12};
int[] arr2 = {1, 2, 2, 3, 4, 15, 9, 7, 12, 14};
printIntersect(arr1, arr2);
}
private static void printIntersect(int[] arr1, int[] arr2) {
Map<Integer, Integer> map = new HashMap<>();
//put first array to map
for (int i = 0; i < arr1.length; i++) {
if (!map.containsKey(arr1[i])) {
map.put(arr1[i], 1);
} else {
map.put(arr1[i], map.get(arr1[i]) + 1);
}
}
//check all value in array two
for (int i = 0; i < arr2.length; i++) {
//if exist and value>1 then decrement value
//if value is 1 remove from map
if (map.containsKey(arr2[i])) {
System.out.print(arr2[i] + " ");
if (map.get(arr2[i]) > 1) {
map.put(arr2[i], map.get(arr2[i]) - 1);
} else {
map.remove(arr2[i]);
}
}
}
}
if the arrays are sorted
int a1[]=new int[] {1,2,3,5,7,8};
int a2[]=new int [] {1,5,6,7,8,9};
// get the length of both the array
int n1=a1.length;
int n2=a2.length;
//create a new array to store the intersection
int a3[]=new int[n1];
//run the loop and find the intersection
int i=0,j=0,k=0;
while(i<n1&& j<n2) {
if(a1[i]<a2[j]) {
// a1 element at i are smaller than a2 element at j so increment i
i++;
}else if(a1[i]>a2[j]) {
// a2 element at i are smaller than a2 element at j so increment j
j++;
}else {
// intersection element store the value and increment i, j, k to find the next element
a3[k]=a1[i];
i++;
j++;
k++;
}
}
for(int l=0;l<a3.length;l++) {
System.out.println(a3[l]);
}
How to Find the Intersection of 3 unsorted arrays in Java:-
I have used the Core Java approach using for loops & using Arrays.copyOf to achieve this.
public class Intersection {
public void intersection3Arrays(int ar1[], int ar2[], int ar3[]) {
Arrays. sort(ar1);
Arrays. sort(ar2);
Arrays. sort(ar3);
int ar1Len = ar1.length;
int ar2Len = ar2.length;
int ar3Len = ar3.length;
int larArray = ar3Len > (ar1Len > ar2Len ? ar1Len : ar2Len) ? ar3Len : ((ar1Len > ar2Len) ? ar1Len : ar2Len);
System.out.println("The largest array is " +larArray);
int[] inputArray1 = Arrays.copyOf(ar1, larArray);
int[] inputArray2 = Arrays.copyOf(ar2, larArray);
int[] inputArray3 = Arrays.copyOf(ar3, larArray);
Integer[] inputArray11 = new Integer[inputArray1.length];
Integer[] inputArray22 = new Integer[inputArray2.length];
Integer[] inputArray33 = new Integer[inputArray3.length];
for (int i = 0; i < inputArray11.length; i++) {
if (inputArray11[i] == null){
inputArray1[i] = 0;
}
}
for (int i = 0; i < inputArray22.length; i++) {
if (inputArray22[i] == null){
inputArray1[i] = 0;
}
}
for (int i = 0; i < inputArray33.length; i++) {
if (inputArray33[i] == null){
inputArray1[i] = 0;
}
}
for (int i = 0; i < inputArray11.length; i++)
for (int j = 0; j < inputArray22.length; j++)
for (int k = 0; k < inputArray33.length; j++)
if (inputArray11[i] == inputArray22[j] && inputArray11[i] == inputArray33[k]) {
System.out.print(inputArray11[i]+" ");
}
}
public static void main(String[] args) {
Intersection3Arrays arrays = new Intersection3Arrays();
int ar1[] = { 1, 2, 5, 10, 20, 40, 80 };
int ar2[] = { 80, 100, 6, 2, 7, 20 };
int ar3[] = {3, 4, 15, 20, 30, 70, 80, 120};
arrays.intersection3Arrays(ar1, ar2, ar3);
}
}
If you ever wanted to implement this in python, this is one way that you can find intersection.
#find intersection
def find_intersec(list_a, list_b):
return set(list_a).intersection(list_b)
#since lists are kind of like arrays in python we use two lists
list_a = [ 4, 9, 1, 17, 11, 26, 28, 10,28, 26, 66, 91]
list_b = [9, 9, 74, 21, 45, 11, 63,10]
print(find_intersec(list_a, list_b))
I hope this example will simple one.pass two arrays and you will definitely get INTERSECTION of array without duplicate items.
private static int[] findInterserctorOfTwoArray(int[] array1, int[] array2) {
Map<Integer,Integer> map=new HashMap<>();
for (int element : array1) {
for (int element2 : array2) {
if(element==element2) {
map.put(element, element);
}
}
}
int[] newArray=new int[map.size()];
int con=0;
for(Map.Entry<Integer, Integer> lst:map.entrySet()) {
newArray[con]=lst.getValue();
con++;
}
return newArray;
}
optimised for sorted arrays using only one loop.
int a1[]=new int[] {1,2,3,5,7,8};
int a2[]=new int [] {1,5,6,7,8,9};
// sort both the array
Arrays.sort(a1);
Arrays.sort(a2);
// get the length of both the array
int n1=a1.length;
int n2=a2.length;
//create a new array to store the intersection
int a3[]=new int[n1];
//run the loop and find the intersection
int i=0,j=0,k=0;
while(i<n1&& j<n2) {
if(a1[i]<a2[j]) {
// a1 element at i are smaller than a2 element at j so increment i
i++;
}else if(a1[i]>a2[j]) {
// a2 element at i are smaller than a2 element at j so increment j
j++;
}else {
// intersection element store the value and increment i, j, k to find the next element
a3[k]=a1[i];
i++;
j++;
k++;
}
}
for(int l=0;l<a3.length;l++) {
System.out.println(a3[l]);
}
Primitive Iterator: 6 Times Faster than HashSet
Tested on sorted arrays of 10,000,000 random elements, values between 0 and 200,000,000. Tested on 10 processor i9 with 4GB heap space. Sort time for two arrays was 1.9 seconds.
results:
primitive() - 1.1 seconds
public static int[] primitive(int[] a1, int[] a2) {
List<Integer> list = new LinkedList<>();
OfInt it1 = Arrays.stream(a1).iterator();
OfInt it2 = Arrays.stream(a2).iterator();
int i1 = it1.next();
int i2 = it2.next();
do {
if (i1==i2) {
list.add(i1);
i1 = it1.next();
}
if (i1 < i2) i1 = it1.next();
if (i2 < i1) i2 = it2.next();
} while(it1.hasNext() && it2.hasNext());
if (i1==i2) list.add(i1);
return list.stream().mapToInt(Integer::intValue).toArray();
}
boxed() - 6.8 seconds
public static int[] boxed(int[] a1, int[] a2) {
return Arrays.stream(a1)
.filter(new HashSet<>(Arrays.stream(a2).boxed()
.collect(Collectors.toList()))::contains)
.toArray();
}

Get the indices of an array after sorting?

Suppose the user enter an array, for example:
Array = {France, Spain, France, France, Italy, Spain, Spain, Italy}
which I did know the length of it
the index array would be:
index = {0, 1, 2, 3, 4, 5, 6, 7}
Now, after sorting it using Arrays.sort(Array);
newArray will be like:
newArray = {France, France, France, Italy, Italy, Spain, Spain, Spain}
and the newIndex will be:
newIndex = {0, 2, 3, 4, 7, 1, 5, 6}
The problem is: how can I find the newIndex from the input Array?
Don't sort the array to start with. Sort the index array, passing in a comparator which compares values by using them as indexes into the array. So you end up with newIndex as the result of the sort, and it's trivial to go from there to the sorted array of actual items.
Admittedly that means sorting an array of integers in a custom way - which either means using an Integer[] and the standard Java library, or a 3rd party library which has an "IntComparator" interface which can be used in conjunction with a sort(int[], IntComparator) type of method.
EDIT: Okay, here's an example comparator. For the sake of simplicity I'll assume you only want to sort an "original" array of strings... and I won't bother with nullity testing.
public class ArrayIndexComparator implements Comparator<Integer>
{
private final String[] array;
public ArrayIndexComparator(String[] array)
{
this.array = array;
}
public Integer[] createIndexArray()
{
Integer[] indexes = new Integer[array.length];
for (int i = 0; i < array.length; i++)
{
indexes[i] = i; // Autoboxing
}
return indexes;
}
#Override
public int compare(Integer index1, Integer index2)
{
// Autounbox from Integer to int to use as array indexes
return array[index1].compareTo(array[index2]);
}
}
You'd use it like this:
String[] countries = { "France", "Spain", ... };
ArrayIndexComparator comparator = new ArrayIndexComparator(countries);
Integer[] indexes = comparator.createIndexArray();
Arrays.sort(indexes, comparator);
// Now the indexes are in appropriate order.
Concise way of achieving this with Java 8 Stream API,
final String[] strArr = {"France", "Spain", "France"};
int[] sortedIndices = IntStream.range(0, strArr.length)
.boxed().sorted((i, j) -> strArr[i].compareTo(strArr[j]) )
.mapToInt(ele -> ele).toArray();
TreeMap<String,Int> map = new TreeMap<String,Int>();
for( int i : indexes ) {
map.put( stringarray[i], i );
}
Now iterator over map.values() to retrieve the indexes in sort order, and over map.keySet() to get the strings, or over map.entrySet() to get the String-index-Pairs.
If having a scenario of repeatedly sorting primitive float or int arrays with positive values, then a method like below yields much better (x3~x4) speed compared to using any comparators:
long time = System.currentTimeMillis();
for (int i = 0; i < iters; i++) {
float[] array = RandomUtils.randomFloatArray(-1, 1, 3000);
long[] valueKeyPairs = new long[array.length];
for (int j = 0; j < array.length; ++j) {
valueKeyPairs[j] = (((long) Float.floatToIntBits(array[j])) << 32) | (j & 0xffffffffL);
}
Arrays.sort(valueKeyPairs);
/**Then use this to retrieve the original value and index*/
//long l = valueKeyPairs[j];
//float value = Float.intBitsToFloat((int) (l >> 32));
//int index = (int) (l);
}
long millis = System.currentTimeMillis() - time;
I made the following based on #Skeet's code. I think it is a little more OOPie. I dunno.
public static <T extends Comparable<T>> List<Integer> sortIndex(List<T> in) {
ArrayList<Integer> index = new ArrayList<>();
for (int i = 0; i < in.size(); i++) {
index.add(i);
}
Collections.sort(index, new Comparator<Integer>() {
#Override
public int compare(Integer idx1, Integer idx2) {
return in.get(idx1).compareTo(in.get(idx2));
}
});
return index;
}
Instead of the class that implements the sorting and indexing having the Comparator code for the different objects coming in, the objects in the original array must implement the Comparable interface. It seems many objects of interest have a natural ordering and have the Comparable interface implemented already.
public static void main(String[] args) {
List<Integer> a1 = new ArrayList<>(Arrays.asList(2, 3, 9, 4, 1));
// Just pass in the list to have its indexes sorted by the natural ordering
List<Integer> idx = sortIndex(a1);
List<Double> a2 = new ArrayList<>(Arrays.asList(1.0, 5.3, 5.2, -3.1, 0.3));
idx = sortIndex(a2);
List<numBits> a3 = new ArrayList<>();
for (int i = 0; i < 10; i++) {
a3.add(new numBits(i));
}
// If you need to sort the indexes of your own object, you must implement
// the Comparable Interface.
idx = sortIndex(a3);
}
static class numBits implements Comparable<numBits> {
private int a;
public numBits(int i) {
a = i;
}
public String toString() {
return Integer.toString(a);
}
// Sort by the total number of bits in the number.
#Override
public int compareTo(numBits that) {
if (Integer.bitCount(this.a) < Integer.bitCount(that.a))
return -1;
if (Integer.bitCount(this.a) > Integer.bitCount(that.a))
return 1;
return 0;
}
}
One way you could do this is to Wrap the original index and country name into a separate Class. Then sort the Array based on the names. This way, your original indexes will be preserved.
What Comes at first Glance is Map them like that
Map <Integer, String> map = new HashMap<Integer, String>();
map.put(0, "France");
map.put(1, "Spain");
map.put(2, "France");
and then sort them by value like that and then you can know their indexes and values (key, values) just print the map
Iterator mapIterator = map.keySet().iterator();
while (mapIterator .hasNext()) {
String key = mapIterator.next().toString();
String value = map.get(key).toString();
System.out.println(key + " " + value);
}
i found solution.
List<String> a = {b, a, d, c};
List<Integer> b = {2, 1, 4, 3};
and if a sort
private void setsortb() {
List<String> beforeA = new ArrayList<>();
List<Integer> beforeB = new ArrayList<>();
beforeA.addAll(a);
beforeB.addAll(b);
a.sort();//change like this {a, b, c, d}
for(int i = 0; i < beforeA.size(); i++) {
int index = beforeA.indexOf(a.get(i));
b.set(i, beforeB.get(i));
}
}
like this
result
a = {a, b, c, d}
b = {1, 2, 3, 4}

How to sort an array of ints using a custom comparator?

I need to sort an array of ints using a custom comparator, but Java's library doesn't provide a sort function for ints with comparators (comparators can be used only with objects). Is there any easy way to do this?
If you can't change the type of your input array the following will work:
final int[] data = new int[] { 5, 4, 2, 1, 3 };
final Integer[] sorted = ArrayUtils.toObject(data);
Arrays.sort(sorted, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
// Intentional: Reverse order for this demo
return o2.compareTo(o1);
}
});
System.arraycopy(ArrayUtils.toPrimitive(sorted), 0, data, 0, sorted.length);
This uses ArrayUtils from the commons-lang project to easily convert between int[] and Integer[], creates a copy of the array, does the sort, and then copies the sorted data over the original.
How about using streams (Java 8)?
int[] ia = {99, 11, 7, 21, 4, 2};
ia = Arrays.stream(ia).
boxed().
sorted((a, b) -> b.compareTo(a)). // sort descending
mapToInt(i -> i).
toArray();
Or in-place:
int[] ia = {99, 11, 7, 21, 4, 2};
System.arraycopy(
Arrays.stream(ia).
boxed().
sorted((a, b) -> b.compareTo(a)). // sort descending
mapToInt(i -> i).
toArray(),
0,
ia,
0,
ia.length
);
You can use IntArrays.quickSort(array, comparator) from fastutil library.
If you don't want to copy the array (say it is very large), you might want to create a wrapper List<Integer> that can be used in a sort:
final int[] elements = {1, 2, 3, 4};
List<Integer> wrapper = new AbstractList<Integer>() {
#Override
public Integer get(int index) {
return elements[index];
}
#Override
public int size() {
return elements.length;
}
#Override
public Integer set(int index, Integer element) {
int v = elements[index];
elements[index] = element;
return v;
}
};
And now you can do a sort on this wrapper List using a custom comparator.
You don't need external library:
Integer[] input = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(input, (a, b) -> b - a); // reverse order
return Arrays.stream(input).mapToInt(Integer::intValue).toArray();
By transforming your int array into an Integer one and then using public static <T> void Arrays.sort(T[] a,
Comparator<? super T> c) (the first step is only needed as I fear autoboxing may bot work on arrays).
java 8:
Arrays.stream(new int[]{10,4,5,6,1,2,3,7,9,8}).boxed().sorted((e1,e2)-> e2-e1).collect(Collectors.toList());
If you are interested with performance and reducing number of object created on the way consider using implementation from eclipse collections.
It uses custom IntComparator, which operates on primitives thus no boxing is required.
Here is some code (it's actually not Timsort as I originally thought, but it does work well) that does the trick without any boxing/unboxing. In my tests, it works 3-4 times faster than using Collections.sort with a List wrapper around the array.
// This code has been contributed by 29AjayKumar
// from: https://www.geeksforgeeks.org/sort/
static final int sortIntArrayWithComparator_RUN = 32;
// this function sorts array from left index to
// to right index which is of size atmost RUN
static void sortIntArrayWithComparator_insertionSort(int[] arr, IntComparator comparator, int left, int right) {
for (int i = left + 1; i <= right; i++)
{
int temp = arr[i];
int j = i - 1;
while (j >= left && comparator.compare(arr[j], temp) > 0)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
// merge function merges the sorted runs
static void sortIntArrayWithComparator_merge(int[] arr, IntComparator comparator, int l, int m, int r) {
// original array is broken in two parts
// left and right array
int len1 = m - l + 1, len2 = r - m;
int[] left = new int[len1];
int[] right = new int[len2];
for (int x = 0; x < len1; x++)
{
left[x] = arr[l + x];
}
for (int x = 0; x < len2; x++)
{
right[x] = arr[m + 1 + x];
}
int i = 0;
int j = 0;
int k = l;
// after comparing, we merge those two array
// in larger sub array
while (i < len1 && j < len2)
{
if (comparator.compare(left[i], right[j]) <= 0)
{
arr[k] = left[i];
i++;
}
else
{
arr[k] = right[j];
j++;
}
k++;
}
// copy remaining elements of left, if any
while (i < len1)
{
arr[k] = left[i];
k++;
i++;
}
// copy remaining element of right, if any
while (j < len2)
{
arr[k] = right[j];
k++;
j++;
}
}
// iterative sort function to sort the
// array[0...n-1] (similar to merge sort)
static void sortIntArrayWithComparator(int[] arr, IntComparator comparator) { sortIntArrayWithComparator(arr, lIntArray(arr), comparator); }
static void sortIntArrayWithComparator(int[] arr, int n, IntComparator comparator) {
// Sort individual subarrays of size RUN
for (int i = 0; i < n; i += sortIntArrayWithComparator_RUN)
{
sortIntArrayWithComparator_insertionSort(arr, comparator, i, Math.min((i + 31), (n - 1)));
}
// start merging from size RUN (or 32). It will merge
// to form size 64, then 128, 256 and so on ....
for (int size = sortIntArrayWithComparator_RUN; size < n; size = 2 * size)
{
// pick starting point of left sub array. We
// are going to merge arr[left..left+size-1]
// and arr[left+size, left+2*size-1]
// After every merge, we increase left by 2*size
for (int left = 0; left < n; left += 2 * size)
{
// find ending point of left sub array
// mid+1 is starting point of right sub array
int mid = Math.min(left + size - 1, n - 1);
int right = Math.min(left + 2 * size - 1, n - 1);
// merge sub array arr[left.....mid] &
// arr[mid+1....right]
sortIntArrayWithComparator_merge(arr, comparator, left, mid, right);
}
}
}
static int lIntArray(int[] a) {
return a == null ? 0 : a.length;
}
static interface IntComparator {
int compare(int a, int b);
}
Here is a helper method to do the job.
First of all you'll need a new Comparator interface, as Comparator doesn't support primitives:
public interface IntComparator{
public int compare(int a, int b);
}
(You could of course do it with autoboxing / unboxing but I won't go there, that's ugly)
Then, here's a helper method to sort an int array using this comparator:
public static void sort(final int[] data, final IntComparator comparator){
for(int i = 0; i < data.length + 0; i++){
for(int j = i; j > 0
&& comparator.compare(data[j - 1], data[j]) > 0; j--){
final int b = j - 1;
final int t = data[j];
data[j] = data[b];
data[b] = t;
}
}
}
And here is some client code. A stupid comparator that sorts all numbers that consist only of the digit '9' to the front (again sorted by size) and then the rest (for whatever good that is):
final int[] data =
{ 4343, 544, 433, 99, 44934343, 9999, 32, 999, 9, 292, 65 };
sort(data, new IntComparator(){
#Override
public int compare(final int a, final int b){
final boolean onlyNinesA = this.onlyNines(a);
final boolean onlyNinesB = this.onlyNines(b);
if(onlyNinesA && !onlyNinesB){
return -1;
}
if(onlyNinesB && !onlyNinesA){
return 1;
}
return Integer.valueOf(a).compareTo(Integer.valueOf(b));
}
private boolean onlyNines(final int candidate){
final String str = String.valueOf(candidate);
boolean nines = true;
for(int i = 0; i < str.length(); i++){
if(!(str.charAt(i) == '9')){
nines = false;
break;
}
}
return nines;
}
});
System.out.println(Arrays.toString(data));
Output:
[9, 99, 999, 9999, 32, 65, 292, 433, 544, 4343, 44934343]
The sort code was taken from Arrays.sort(int[]), and I only used the version that is optimized for tiny arrays. For a real implementation you'd probably want to look at the source code of the internal method sort1(int[], offset, length) in the Arrays class.
I tried maximum to use the comparator with primitive type itself. At-last i concluded that there is no way to cheat the comparator.This is my implementation.
public class ArrSortComptr {
public static void main(String[] args) {
int[] array = { 3, 2, 1, 5, 8, 6 };
int[] sortedArr=SortPrimitiveInt(new intComp(),array);
System.out.println("InPut "+ Arrays.toString(array));
System.out.println("OutPut "+ Arrays.toString(sortedArr));
}
static int[] SortPrimitiveInt(Comparator<Integer> com,int ... arr)
{
Integer[] objInt=intToObject(arr);
Arrays.sort(objInt,com);
return intObjToPrimitive(objInt);
}
static Integer[] intToObject(int ... arr)
{
Integer[] a=new Integer[arr.length];
int cnt=0;
for(int val:arr)
a[cnt++]=new Integer(val);
return a;
}
static int[] intObjToPrimitive(Integer ... arr)
{
int[] a=new int[arr.length];
int cnt=0;
for(Integer val:arr)
if(val!=null)
a[cnt++]=val.intValue();
return a;
}
}
class intComp implements Comparator<Integer>
{
#Override //your comparator implementation.
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o1.compareTo(o2);
}
}
#Roman:
I can't say that this is a good example but since you asked this is what came to my mind.
Suppose in an array you want to sort number's just based on their absolute value.
Integer d1=Math.abs(o1);
Integer d2=Math.abs(o2);
return d1.compareTo(d2);
Another example can be like you want to sort only numbers greater than 100.It actually depends on the situation.I can't think of any more situations.Maybe Alexandru can give more examples since he say's he want's to use a comparator for int array.

Categories