数组倒序问题(采用递归方法)

前一段时间去参加阿里巴巴面试,被面试官问到采用递归实现数组倒序,当时头脑不在状态竟没写出来,果断被炮灰了。

数组倒序:

实例:初始数组a={1,3,7,5}

      倒序后数组a={5,7,3,1}

代码:

package edu.test.algorithm;

public class ReverseArray {
    public void reverse(int a[],int first,int end){
        if(first<end){
            reverse(a,first+1,end-1);
            exchange(a,first,end);
        }
        
    }
    public void exchange(int a[],int i,int j){
        int temp=a[i];
        a[i]=a[j];
        a[j]=temp;
    }
    public static void main(String[] args) {
        ReverseArray ra=new ReverseArray();
        int a[]={1,3,4,0};
        ra.reverse(a, 0, a.length-1);
        for(int temp:a){
            System.out.println(temp);
        }
    }

}

 

posted @ 2014-09-25 19:20  big sun  阅读(476)  评论(0)    收藏  举报