交换数组中的引用

时间:2014-01-25 00:36:12

标签: java arrays swap

好的,我误解了这个问题。读了几次之后,我发现randInt实际上是我用来填充数组的方法本身。因此,当我说要调用randInt某种递归调用时,我认为。这在某种程度上应该是什么样子:

  static int[] randInt(int i, int j) {
    int[] temp = new int[(j - i) + 1];
    for ( i = 0; i < j; i++) {
        temp[i] = i + 1; // here i populate the array
    }
    System.out.println(Arrays.toString(temp)); // this prints [1, 2, 3, 4, 5]
    for ( i = 1; i < j;i++){
        swapReferences(temp[i], temp[randInt(0,i)] ); //this is some sort of recursive call that swaps the references 
        // btw that statement does not compile, how can i pass a method as a parameter?



    }
    return temp;
}

static void swapReferences(int a, int b) { //these parameters are wrong, need to be changed
   //Method to swap references

}

对于这种混乱感到抱歉,但我认为这应该是正确的。

2 个答案:

答案 0 :(得分:2)

Java是按值传递的,因此在您尝试重新分配参数时将无效。

您需要做的是将数组本身和两个整数索引作为参数:

 int randInt = generate.nextInt(j-i) + 1; //this is gonna generate a # within the range of the array (so if array is size 5, generates something 1-5)
 for ( i = 1; i < j;i++){
        swapReferences(temp, i, randInt); //and this is my attempt at swapping the references
        randInt = generate.nextInt(i) + 1 ;
  }

  static void swapReferences(int[] array, int a, int b){
     int x = array[a];
     array[a] = array[b];
     array[b] = x;

 }

可以改变参数,例如传递给方法的数组,就像这里所做的那样,但你不能自己重新分配参数。

答案 1 :(得分:2)

您只是更改a和b指向的整数,而不是数组指向的指标。您需要更改swapReferences方法以将数组作为输入,以及类似交换的指示

static void swapReferences(int[] arr, int indexA, int index B){
    int x = arr[indexA];
    a = arr[indexB];
    b = x;
    arr[indexA] = a;
    arr[indexB] = b;
}

static void swapReferences(int[] arr, int indexA, int indexB){
    int x = arr[indexA];
    arr[indexA] = arr[indexB];
    arr[indexB] = x;
}