簡體   English   中英

Java,遞歸反轉一個數組

[英]Java, recursively reverse an array

我還沒有找到任何符合我的 function 的特定需求的東西來做這個,是的,它是用於家庭作業的。

所以我有:

public void reverseArray(int[] x) {

}

前提條件:x.length > 0

我不能讓 function 返回任何東西,唯一的論點是一個數組,這讓我很困惑。

我嘗試使用循環和遞歸,但我嘗試的一切似乎都以生成 function 的無限實例而告終。

我已經有了一個想法/建議來使用另一個 function 和這個,但是,如何遞歸地使用原始文件目前超出了我的范圍。

任何幫助表示贊賞。

void reverseArray(int[] x){
   reverse(x, 0, x.length -1);
}

void reverse(int[] x, int i, int j){
    if(i<j){//Swap
       int tmp = x[i];
       x[i] = x[j];
       x[j] = tmp;
       reverse(x, ++i, --j);//Recursive
    }   
}

測試:

int[] s = new int[]{1,2,3,4,5};
reverseArray(s);
System.out.println(Arrays.toString(s));//"5,4,3,2,1"

遞歸,O(n),不需要臨時數組。

如果我正在編寫這個,我會創建一個臨時數組(可能有一個元素被刪除?),用於遞歸調用,並在從函數返回之前將元素復制回原始數組。 您還需要找到一個基本案例來終止遞歸。

因為這是你的功課,我建議一個例子:

給定順序: 1 2 3 4 5 6 7 8 9 10

你可以改為: 10 2 3 4 5 6 7 8 9 1

之后: 10 9 3 4 5 6 7 8 2 1

.....

如您所見,一步一步,序列“更好”,問題是“更小”。 那么,你應該解決的問題是:

1)如何對此方法應用遞歸調用。 對於原始方法,方法是: reverse(int[] a) 所以,在第一步之后,你應該b from a[2] --> a[n-1]創建數組b from a[2] --> a[n-1] 並使用reverse(int [] b)`。

2)反轉b ,我們該怎么做才能扭轉? 再次將b的值分配回a。

3)停止條件:什么停止條件? 您會看到數組b的元素少於數組a的元素。 那么,到哪一步,我們應該停下來?

希望這有幫助:)

嘗試以下內容:

public void reverseArray(int[] x) {
    if(x.length ==2){
      //if two elements, swap them
      int first = x[0];
      x[0] = x[1];
      x[1] = first;
    }else if(x.length > 2){
      //swap first and last
      int first = x[0];
      x[0]= x[x.length-1];
      x[x.length-1] = first;
      //create a copy of middle elements
      int [] copy = new int[x.length-2];
      System.arraycopy( x, 1, copy, 0, x.length-2);
      //recursive call for middle elements
      reverseArray(copy);
      //place the reversed elements back in the original array
      System.arraycopy( copy, 0, x, 1, copy.length);
    }
}

在這里調用reverseArray(0,n,arr)n是數組的長度

public void reverseArray(int i, int n, int [] arr)
{
   if(i==n)
   {
     return ;
   } 
   else
   {
     reverseArray(i+1, n, arr);
     System.out.println(arr.at(i));
   }
}

//我們只是在這里做一個操作並調用一個幫助方法。

public void reverseArray(int[] nums){
  int[] hold = new int[nums.length]; //just so it will take this argument
  int[] reversed = recurReverseArray(nums, hold, nums.length - 1, 0);
  nums = reversed; //not returning just changing nums to be reversed.
}
public int[] recurReverseArray(int[] nums, int[] reverse, int end, int start){
  if(end == 0 && start == nums.length - 1){
  reverse[start] = nums[end];
  return reverse; //the way out.
  }
  reverse[start] = nums[end];
  return recurReverseArray(nums, reverse, end - 1, start + 1);
}

這是主要方法:

package main;

public class Main {
    public static void main(String[] args) {
        StringOps ops = new StringOps();
        String string = "Arjun";
        // reversing the string recrusively
        System.out.println(ops.reverseRecursively(string.toCharArray(), 0));
    }
}

這是遞歸函數:

package main;

public class StringOps {
    public char[] reverseRecursively(char[] array, int i) {
        char[] empty = new char[0];
        if (array.length < 1) {
            System.out.println("you entered empty string");
            return empty;
        }
        char temp;
        temp = array[i];
        array[i] = array[array.length - 1 - i];
        array[array.length - 1 - i] = temp;
        i++;

        if (i >= array.length - 1 - i) {
            return array;
        } else {
            reverseRecursively(array, i);
            return array;
        }

    }

}
public class FunWithAlgorthims {


public static void main(final String[] args) {

    String[] array = {"a", "b", "c", "d"};
    printArray(array);
    revereArrayRecusrive(array, 0);
    printArray(array);
}


public static void revereArrayRecusrive(final String[] array, int startPointer) {
    if (startPointer >= (array.length / 2)) {
        return;
    }
    String temp = array[startPointer];
    array[startPointer] = array[array.length - 1 - startPointer];
    array[array.length - 1 - startPointer] = temp;
    revereArrayRecusrive(array, ++startPointer);
}

public static void printArray(final String[] array) {
    Arrays.stream(array).forEach(a -> System.out.print(a + " "));
    System.out.println();
}

}

這可能是最簡單的方法,不是最快的,但可能是最簡單的方法。

整個程序看起來像這樣:

public static void main(String [] args)
{
    BackwardsArray back = new BackwardsArray();
}

public BackwardsArray()
{
    int [] a = {1,2,3,4,5,6,7,8,9};
    printBackwards(a);
}

void printBackwards( int [] b)
{
    print(b,b.length-1);
}

void print(int [] b, int pos)
{
    System.out.println(b[pos]); // prints last item
    if(pos != 0)
    {
        print(b,pos-1);
    }
}

希望能幫助到你!

public class RecursiveArray {


   public static int[] backWardArray(int[] arr, int start, int end) {

       if (start < end) {
           int temp = arr[start];
           arr[start] = arr[end];
           arr[end] = temp;
           backWardArray(arr, start + 1, end - 1);
       }
       return arr;
   }

    public static void main(String[] args) {
        int [] arr = {12,4,6,8,9,2,1,0};
    int [] reversedArray= backWardArray(arr, 0, arr.length-1);
    //loop through the reversed array
        for (int i: reversedArray) {
            System.out.println(i);
        }
    }

    public RecursiveArray() {
    }
}
private static void reversePrint(int[] numbers)
{
    if(numbers.length==0) {
        return;
    }
    int[] a = new int[numbers.length -1];
    for(int i =0;i<numbers.length-1;i++) {
        a[i] = numbers[i+1];
    }
    reversePrint(a);
    System.out.println(numbers[0]+" ");

}
Simple solution:
int[] arr = { 1, 3, 4, 56, 6 };
int[] ans = new int[arr.length];
int num = arr.length-1;
for (int i = 0; i < arr.length; i++) {
   ans[i] = arr[num];
   System.out.println(ans[i]);
   num--;
}

偽代碼

function revarray(a[1...n])
  if a.length == 1 or a.length == 0
    do nothing 
  # return a
  else
     swap a[1] and a[n]
     revarray(a[2...n-1])
  # return a (The function will not return anything but the contents of a are changed)

由於沒有聲明不能使用循環:

void reverseArray(int[] x) {
    if (x != null) {
        for (int i = 0; i < length.x / 2; i++) {
            int j = (length.x - 1) - i;
            int temp = x[i];
            x[i] = x[j];
            x[j] = temp;
         }
         reverseArray(null);
     }
}

可能是最快的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM