实例042 反转数组中元素的顺序

实例042 反转数组中元素的顺序

实例说明

反转数组就是以相反的顺序把原有数组的内容重新排序。本实例在GUI窗体中演示反转数组中元素的顺序。运行本实例,首先在界面的文本框内输入数组元素,每个元素使用空格分隔,然后单击界面上的“反转数组元素”按钮,程序将对数组进行反转运算,并把运算过程中对数组的改变显示在窗体中。实例的运行效果如图516所示。

反转和倒序排序的区别

脚下留神:“反转”并不等于“倒序排序”。

  • “反转”只是将数组元素的顺序进行颠倒,并不对其执行排序操作;
  • 而“倒序排序”则是对数组中的元素进行从大到小的排序。

实现过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void reverseArray(int[] array)
{
int temp;
int i_thFromLast;
for (int i = 0; i < array.length / 2; i++)
{
// 计算倒数第i个元素的索引
i_thFromLast = array.length - 1 - i;
// 将第i个元素和倒数第i个元素交换
temp = array[i];
array[i] = array[i_thFromLast];
array[i_thFromLast] = temp;
printSwapStep(array, i_thFromLast, i);
}
}

技术要点

本实例的核心技术是使用了数组反转算法。反转算法的基本思想比较简单,也很好理解,思路就是:

  • 把数组最后一个元素与第一个元素替换,
  • 倒数第二个元素与第二个元素替换,
  • 依此类推,直到把所有数组元素反转替换。

反转数组元素是对数组两边的元素进行替换,所以只需要循环数组长度的半数。例如,对长度为6的一维数组进行反转,只需要循环6/2,即3次,具体的反转过程如图517所示

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package com.lan;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

public class ReverseArray extends JFrame
{
private final class ReverseButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String[] arrayStrs = textAreaInput.getText().split(",");
int[] array = new int[arrayStrs.length];
for (int i = 0; i < array.length; i++)
{
array[i] = Integer.parseInt(arrayStrs[i]);
}
reverseArray(array);
}
private void reverseArray(int[] array)
{
int temp;
int i_thFromLast;
for (int i = 0; i < array.length / 2; i++)
{
// 计算倒数第i个元素的索引
i_thFromLast = array.length - 1 - i;
// 将第i个元素和倒数第i个元素交换
temp = array[i];
array[i] = array[i_thFromLast];
array[i_thFromLast] = temp;
printSwapStep(array, i_thFromLast, i);
}
}
private void printSwapStep(int[] array, int i_thFromLast, int i)
{
for (int j = 0; j < array.length; j++)
{
if (j == i)
{
textAreaShow.append("[");
}
textAreaShow.append(String.valueOf(array[j]));
if (j == i_thFromLast)
{
textAreaShow.append("]");
}
if (j < array.length - 1)
{
textAreaShow.append(",");
}
}
textAreaShow.append("\n");
}
}

private static final long serialVersionUID = 5911081012919816847L;
private JPanel contentPane;
private JTextArea textAreaShow = new JTextArea();
private JTextArea textAreaInput = new JTextArea();
private final JMenuBar menuBar = new JMenuBar();
private final JMenu menu = new JMenu("菜单");
private final JMenuItem menuItem = new JMenuItem("退出");

/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run()
{
try
{
ReverseArray frame = new ReverseArray();
frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public ReverseArray() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
dispose();
}
});
// 为菜单设置alt+f快捷键(助记符)
menu.setMnemonic('F');
GridBagConstraints gbc_menuBar = new GridBagConstraints();
gbc_menuBar.anchor = GridBagConstraints.EAST;
gbc_menuBar.gridx = 0;
gbc_menuBar.gridy = 0;

contentPane.add(menuBar, gbc_menuBar);
menuBar.add(menu);
menu.add(menuItem);
// 为菜单项设置快捷键
KeyStroke Ctrl_Shift_W = KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.CTRL_DOWN_MASK + KeyEvent.SHIFT_DOWN_MASK);
menuItem.setAccelerator(Ctrl_Shift_W);

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);

JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
"\u8F93\u5165\u6570\u7EC4\u5143\u7D20,\u4EE5\u82F1\u6587\u9017\u53F7\u5206\u9694,\u5982:1,2,3,4,5", TitledBorder.LEFT,
TitledBorder.TOP, null, new Color(0, 0, 0)));
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.insets = new Insets(0, 0, 5, 0);
gbc_panel.gridx = 0;
gbc_panel.gridy = 1;
contentPane.add(panel, gbc_panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0};
gbl_panel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);

GridBagConstraints gbc_textAreaInput = new GridBagConstraints();
gbc_textAreaInput.fill = GridBagConstraints.BOTH;
gbc_textAreaInput.gridx = 0;
gbc_textAreaInput.gridy = 0;
panel.add(textAreaInput, gbc_textAreaInput);

JButton buttonReverse = new JButton("反转数组");
// 为按钮绑定组合快捷键
buttonReverse.registerKeyboardAction(new ReverseButtonListener(), KeyStroke.getKeyStroke(KeyEvent.VK_B, KeyEvent.CTRL_DOWN_MASK),
JComponent.WHEN_IN_FOCUSED_WINDOW);
buttonReverse.addActionListener(new ReverseButtonListener());
GridBagConstraints gbc_buttonReverse = new GridBagConstraints();
gbc_buttonReverse.insets = new Insets(0, 0, 5, 0);
gbc_buttonReverse.gridx = 0;
gbc_buttonReverse.gridy = 2;
contentPane.add(buttonReverse, gbc_buttonReverse);

GridBagConstraints gbc_textAreaShow = new GridBagConstraints();
gbc_textAreaShow.insets = new Insets(0, 0, 5, 0);
gbc_textAreaShow.fill = GridBagConstraints.BOTH;
gbc_textAreaShow.gridx = 0;
gbc_textAreaShow.gridy = 3;
contentPane.add(textAreaShow, gbc_textAreaShow);
}
}

Swing设置组合快捷键

为菜单 设置alt+X快捷键

1
2
3
4
5
private final JMenu menu = new JMenu("菜单");
......
// 为菜单设置alt+f快捷键(助记符)
menu.setMnemonic('F');
......

为菜单项设置组合快捷键

1
2
3
4
5
6
7
8
9
10
11
12
private final JMenuItem menuItem = new JMenuItem("退出");
........
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
dispose();
}
});
// 为菜单项设置Ctrl+Shif+W快捷键
KeyStroke Ctrl_Shift_W = KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.CTRL_DOWN_MASK + KeyEvent.SHIFT_DOWN_MASK);
menuItem.setAccelerator(Ctrl_Shift_W);
........

为按钮设置Ctrl+xxx组合快捷键

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
......
// 反转数组按钮的时间监听器
private final class ReverseButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String[] arrayStrs = textAreaInput.getText().split(",");
int[] array = new int[arrayStrs.length];
for (int i = 0; i < array.length; i++)
{
array[i] = Integer.parseInt(arrayStrs[i]);
}
reverseArray(array);
}
private void reverseArray(int[] array)
{
int temp;
int i_thFromLast;
for (int i = 0; i < array.length / 2; i++)
{
// 计算倒数第i个元素的索引
i_thFromLast = array.length - 1 - i;
// 将第i个元素和倒数第i个元素交换
temp = array[i];
array[i] = array[i_thFromLast];
array[i_thFromLast] = temp;
printSwapStep(array, i_thFromLast, i);
}
}
private void printSwapStep(int[] array, int i_thFromLast, int i)
{
for (int j = 0; j < array.length; j++)
{
if (j == i)
{
textAreaShow.append("[");
}
textAreaShow.append(String.valueOf(array[j]));
if (j == i_thFromLast)
{
textAreaShow.append("]");
}
if (j < array.length - 1)
{
textAreaShow.append(",");
}
}
textAreaShow.append("\n");
}
}
......
JButton buttonReverse = new JButton("反转数组");
// 为按钮设置事件监听器
buttonReverse.addActionListener(new ReverseButtonListener());
// 为按钮绑定组合快捷键
buttonReverse.registerKeyboardAction(new ReverseButtonListener(), KeyStroke.getKeyStroke(KeyEvent.VK_B, KeyEvent.CTRL_DOWN_MASK),
JComponent.WHEN_IN_FOCUSED_WINDOW);
......