数组
冒泡排序
- 一般时间复杂度为(n^2),优化后最低可以为(n)
package com.Kong.Array;
import java.util.Arrays;
public class ArrayDemo07 {
public static void main(String[] args) {
int[] a={1,2,3,4,5,66666,77,888};
sort(a);
System.out.println(Arrays.toString(a));
}
//冒泡排序
public static int [] sort(int[] a){
//外层循环,判断我们这个要走多少次
for (int i = 0; i < a.length - 1; i++) {
boolean flag = false;//通过flag标识位减少没有意义的比较
//内层循环,比较判断两个数,如果第一个数比第二个数大,就交换位置
for (int j = 0; j < a.length-1-i; j++) {
if (a[j+1] > a[j]) {
int temp = a[j];
a[j] = a[j +1];
a[j+1] = temp;
flag = true;
}
}
if (flag==false) {
break;
}
}
return a;
}
}
稀疏数组
- 需求:编写一个五子棋游戏,有存盘退出和续上盘的功能
package com.Kong.Array;
import java.io.*;
import java.util.Scanner;
public class GobangGame {// 棋盘大小
private static final int ROWS = 15;
private static final int COLS = 15;
// 存档文件
private static final String SAVE_FILE = "gobang_save.dat";
// 玩家标识
private static final int EMPTY = 0;
private static final int BLACK = 1;
private static final int WHITE = 2;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] chessBoard;
int currentPlayer = BLACK; // 默认黑棋先行
System.out.println("===== 五子棋游戏 =====");
System.out.println("1. 新游戏");
System.out.println("2. 读取存档继续游戏");
System.out.print("请选择:");
int choice = scanner.nextInt();
if (choice == 2) {
// 读取存档
int[][] sparseArr = loadFromFile(SAVE_FILE);
if (sparseArr == null) {
System.out.println(" 未找到存档,将开始新游戏");
chessBoard = new int[ROWS][COLS];
} else {
chessBoard = sparseToChess(sparseArr);
// 简单判断当前轮到谁(根据棋子数量奇偶)
int count = sparseArr[0][2];
currentPlayer = count % 2 == 0 ? BLACK : WHITE;
System.out.println(" 存档读取成功!");
}
} else {
// 新游戏
chessBoard = new int[ROWS][COLS];
}
// 游戏主循环
boolean gameOver = false;
while (!gameOver) {
printBoard(chessBoard);
System.out.println("当前轮到:" + (currentPlayer == BLACK ? "黑棋(●)" : "白棋(○)"));
System.out.println("输入格式:行 列(输入-1 -1 存盘退出)");
System.out.print("请输入落子位置:");
int row = scanner.nextInt();
int col = scanner.nextInt();
// 存盘退出
if (row == -1 && col == -1) {
saveGame(chessBoard);
System.out.println(" 游戏已存盘退出!");
break;
}
// 输入合法性检查
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
System.out.println(" 位置超出棋盘范围,请重新输入!");
continue;
}
if (chessBoard[row][col] != EMPTY) {
System.out.println(" 该位置已有棋子,请重新输入!");
continue;
}
// 落子
chessBoard[row][col] = currentPlayer;
// 判断是否五子连珠
if (isWin(chessBoard, row, col, currentPlayer)) {
printBoard(chessBoard);
System.out.println("🎉 " + (currentPlayer == BLACK ? "黑棋" : "白棋") + "获胜!游戏结束");
gameOver = true;
// 游戏结束后删除存档
new File(SAVE_FILE).delete();
continue;
}
// 切换玩家
currentPlayer = (currentPlayer == BLACK) ? WHITE : BLACK;
}
scanner.close();
}
// ------------------------------
// 棋盘 ↔ 稀疏数组 转换
// ------------------------------
public static int[][] chessToSparse(int[][] chessBoard) {
int count = 0;
for (int[] row : chessBoard) {
for (int val : row) {
if (val != EMPTY) count++;
}
}
int[][] sparseArr = new int[count + 1][3];
sparseArr[0][0] = ROWS;
sparseArr[0][1] = COLS;
sparseArr[0][2] = count;
int index = 1;
for (int i = 0; i < chessBoard.length; i++) {
for (int j = 0; j < chessBoard[i].length; j++) {
if (chessBoard[i][j] != EMPTY) {
sparseArr[index][0] = i;
sparseArr[index][1] = j;
sparseArr[index][2] = chessBoard[i][j];
index++;
}
}
}
return sparseArr;
}
public static int[][] sparseToChess(int[][] sparseArr) {
int rows = sparseArr[0][0];
int cols = sparseArr[0][1];
int count = sparseArr[0][2];
int[][] chessBoard = new int[rows][cols];
for (int i = 1; i <= count; i++) {
int row = sparseArr[i][0];
int col = sparseArr[i][1];
int val = sparseArr[i][2];
chessBoard[row][col] = val;
}
return chessBoard;
}
// ------------------------------
// 存盘 / 读盘
// ------------------------------
public static void saveGame(int[][] chessBoard) {
int[][] sparseArr = chessToSparse(chessBoard);
try (PrintWriter writer = new PrintWriter(new FileWriter(SAVE_FILE))) {
for (int[] row : sparseArr) {
writer.println(row[0] + "," + row[1] + "," + row[2]);
}
} catch (IOException e) {
System.out.println(" 存盘失败:" + e.getMessage());
}
}
public static int[][] loadFromFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) return null;
int count = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
while (reader.readLine() != null) count++;
} catch (IOException e) {
e.printStackTrace();
return null;
}
int[][] sparseArr = new int[count][3];
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
int index = 0;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
sparseArr[index][0] = Integer.parseInt(parts[0]);
sparseArr[index][1] = Integer.parseInt(parts[1]);
sparseArr[index][2] = Integer.parseInt(parts[2]);
index++;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return sparseArr;
}
// ------------------------------
// 打印棋盘(带坐标和棋子符号)
// ------------------------------
public static void printBoard(int[][] chessBoard) {
// 打印列号
System.out.print(" ");
for (int j = 0; j < COLS; j++) {
System.out.printf("%2d ", j);
}
System.out.println();
// 打印棋盘
for (int i = 0; i < chessBoard.length; i++) {
System.out.printf("%2d ", i);
for (int val : chessBoard[i]) {
if (val == BLACK) {
System.out.print("● ");
} else if (val == WHITE) {
System.out.print("○ ");
} else {
System.out.print("+ ");
}
}
System.out.println();
}
}
// ------------------------------
// 判断是否五子连珠
// ------------------------------
public static boolean isWin(int[][] chessBoard, int row, int col, int player) {
// 四个方向:横、竖、正斜、反斜
int[][] directions = {{1, 0}, {0, 1}, {1, 1}, {1, -1}};
for (int[] dir : directions) {
int count = 1;
// 正方向
for (int i = 1; i < 5; i++) {
int r = row + dir[0] * i;
int c = col + dir[1] * i;
if (r >= 0 && r < ROWS && c >= 0 && c < COLS && chessBoard[r][c] == player) {
count++;
} else break;
}
// 反方向
for (int i = 1; i < 5; i++) {
int r = row - dir[0] * i;
int c = col - dir[1] * i;
if (r >= 0 && r < ROWS && c >= 0 && c < COLS && chessBoard[r][c] == player) {
count++;
} else break;
}
if (count >= 5) return true;
}
return false;
}
}
介绍
- 当一个数组中大部分元素为0,或者为同一值的数组时,可用稀疏数组来保存
- 稀疏数组的处理方式为:
- 记录数组一共有几行几列,有多少个不同值
- 把具有不同值的元素和行列及值记录在一个小规模的数组中,从而缩小程序的规模
package com.Kong.Array;
public class ArrayDemo08 {
public static void main(String[] args) {
//创建一个二维数组11*11 0:没有棋子 1:黑棋 2:白棋
int[][] arr1 = new int[11][11];
arr1[1][2] = 1;
arr1[2][3] = 2;
System.out.println("输出原始的数组");
for (int[] arr : arr1) {
for (int anArr : arr) {
System.out.print(anArr + "\t");
}
System.out.println();
}
System.out.println("===================");
//转换为稀疏数组
//获取有效值的个数
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (arr1[i][j] != 0) {
sum++;
}
}
}
System.out.println("有效值的个数:" + sum);
//创建一个稀疏数组的数组
int[][] arr2 = new int[sum + 1][3];
arr2[0][0] = 11;
arr2[0][1] = 11;
arr2[0][2] = sum;
//遍历二维数组,将非零的值,存放到稀疏数组
int count = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1[i].length; j++) {
if (arr1[i][j] != 0) {
count++;
arr2[count][0] = i;
arr2[count][1] = j;
arr2[count][2] = arr1[i][j];
}
}
}
System.out.println("稀疏数组");
for (int i = 0; i < arr2.length; i++) {
System.out.println(arr2[i][0] + "\t" + arr2[i][1] + "\t" + arr2[i][2]);
}
System.out.println("===================");
System.out.println("还原稀疏数组");
//读取稀疏数组的值
int[][] arr3 = new int[arr2[0][0]][arr2[0][1]];
//还原其中的值
for (int i = 1; i < arr2.length; i++) {
arr3[arr2[i][0]][arr2[i][1]] = arr2[i][2];
}
for (int i = 0; i < arr3.length; i++) {
for (int j = 0; j < arr3[i].length; j++) {
System.out.print(arr3[i][j] + "\t");
}
System.out.println();
}
}
}