码迷,mamicode.com
首页 > 编程语言 > 详细

数组元素的反转

时间:2019-05-24 23:45:49      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:bsp   存储   public   元素   索引   code   rgs   方式   col   

 1 package com.demo;
 2 
 3 /*
 4  * 数组元素的反转(不使用新数组)
 5  * 实现数组元素的反转,就是把数组中对称位置的元素调换
 6  */
 7 
 8 public class ArrayReverse {
 9     public static void main(String[] args) {
10         // 定义一个数组
11         int[] arr = new int[] { 10, 50, 30, 25, 70, 35 };
12 
13         // 遍历原数组
14         System.out.print("反转前的数组:");
15         for (int i = 0; i < arr.length; i++) {
16             System.out.print(arr[i] + " ");
17         }
18         System.out.println();
19 
20         // 交换对称位置的元素
21         /*
22          * 实现原理:
23          * 定义两个变量来存储索引值
24          *   int first = 0; // 0号索引值
25          *   int last = arr.length - 1; // 最大索引值
26          *   
27          * 1.拿数组中0号索引位置的元素和最大索引位置的元素交换
28          * 2.拿数组中1号索引位置的元素和第二大索引位置的元素交换
29          * 其实就是对称位置的元素进行交换
30          * ......
31          * 以此类推,当  first>=last 的时候,停止交换
32          * 换句话说,交换的条件为:first<last
33          */
34         // 方式一
35         for (int first = 0, last = arr.length - 1; first < last; first++, last--) {
36             int temp = arr[first];
37             arr[first] = arr[last];
38             arr[last] = temp;
39         }
40         
41         // 方式二
42 //        for (int i = 0; i < arr.length / 2; i++) {
43 //            int temp = arr[i];
44 //            arr[i] = arr[arr.length - i - 1];
45 //            arr[arr.length - i - 1] = temp;
46 //        }
47 
48         // 遍历反转后的数组
49         System.out.print("反转后的数组:");
50         for (int i = 0; i < arr.length; i++) {
51             System.out.print(arr[i] + " ");
52         }
53         System.out.println();
54     }
55 }

 

运行结果:

反转前的数组:10 50 30 25 70 35 
反转后的数组:35 70 25 30 50 10 

 

数组元素的反转

标签:bsp   存储   public   元素   索引   code   rgs   方式   col   

原文地址:https://www.cnblogs.com/stefaniee/p/10920743.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!