一維數組轉置


1.首先要知道轉置的話是前面的元素與后面的元素進行交換

2.尋找規律,等到 x=temp[].length-1-x;

3.最后是判斷這個置換的次數,如果每次都置換了,發現並沒改變,那是因為又換回去了,所以循環的次數只有數組長度的一般。

public class 數組轉置 {

	public static void main(String[] args) {
		int[] data=new int[] {1,2,3,4,5,6,7,8};
		print(data);
		transfer(data);
		print(data);
	}
	public static int[] transfer(int[] temp) {
			for(int x=0;x<temp.length/2;x++) {
				int tem=temp[x];
				temp[x]=temp[temp.length-1-x];   
				temp[temp.length-1-x]=tem;
		}
			return temp;
}
		public static void print(int[] temp) {
			for(int x=0;x<temp.length;x++) {
				System.out.print(temp[x]);
			}
			System.out.println();
		}
}

 第二種方法是引用了指針的概念

    把索引當作指向數據的工具

int tem=temp[head];
temp[head]=temp[end];
temp[end]=tem;
head++;
end--;

 下面是完整代碼

public class 數組轉置 {

	public static void main(String[] args) {
		int[] data=new int[] {1,2,3,4,5,6,7,8};
		print(data);
		transfer(data);
		print(data);
	}
	public static int[] transfer(int[] temp) {
		   int head=0;
		   int end=temp.length-1;
		   int center=temp.length/2;
			for(int x=0;x<center;x++) {
				int tem=temp[head];
				temp[head]=temp[end];
				temp[end]=tem;
				head++;
				end--;
		}
			return temp;
}
		public static void print(int[] temp) {
			for(int x=0;x<temp.length;x++) {
				System.out.print(temp[x]);
			}
			System.out.println();
		}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM