user3126841
user3126841

Reputation: 165

How to pass part of an array as function argument in java?

#include<stdio.h>
void fun(int a[],int n)
{
    int i;
    for(i=0;i<n;i++)       
        printf("%d ",a[i]); 
}

int main()
{
    int arr[]={1,2,3,4,5,6};
    fun(arr+2,3);       
    return 0;
}

Output: 3 4 5 The array starting from the 3rd element has been passed here to fun() in C. How to do the same in JAVA, given that there are no such pointers in JAVA?

In response to one comment below I thought to add the details of what I am actually trying to do as it is too long for the comment section. I need to access only a subsection an array recursively. Actually I am trying to find "median of two sorted arrays by comparing the medians of the two arrays" using the following algo : 1) Calculate the medians m1 and m2 of the input arrays ar1[] and ar2[] respectively. 2) If m1 and m2 both are equal then we are done. return m1 (or m2) 3) If m1 is greater than m2, then median is present in one of the below two subarrays. a) From first element of ar1 to m1 (ar1[0...|n/2|]) b) From m2 to last element of ar2 (ar2[|n/2|...n-1]) 4) If m2 is greater than m1, then median is present in one
of the below two subarrays. a) From m1 to last element of ar1 (ar1[|n/2|...n-1]) b) From first element of ar2 to m2 (ar2[0...|n/2|]) 5) Repeat the above process until size of both the subarrays becomes 2. 6) If size of the two arrays is 2 then use below formula to get the median. Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2

Upvotes: 2

Views: 14982

Answers (3)

Christian Tapia
Christian Tapia

Reputation: 34166

If you won't modify the array, you can create a copy of a range using Arrays.copyOfRange(int\[\] original, int from, int to):

import java.util.Arrays;
...
public static void main(String args[])
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    fun(Arrays.copyOfRange(arr, 2, arr.length), 3);
}

public static void fun(int a[], int n)
{
    for (int i = 0; i < n; i++) {
        System.out.printf("%d ", a[i]);
    }
}

Upvotes: 6

DragonZ
DragonZ

Reputation: 39

Because pointer can cause some serious bug or security problems in your program, java does not allow you to manually manipulate pointer as what you can in C. As far as I can think, you have to make a copy of it. You can either use methods from Arrays class provided by java or you can write your own code to do that.

Upvotes: 0

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51553

Easiest way is to pass the start and end indices to the fun method.

public static void main(String args[])
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    fun(arr, 2, 5);
}

public static void fun(int a[], int m, int n)
{
    for (int i = m; i < n; i++) {
        System.out.printf("%d ", a[i]);
    }
}

Response: 3 4 5

Upvotes: 3

Related Questions