Java from beginner to proficient - array (2)

4.Basic operations on arrays

Basic array operations include traversing the array, filling and replacing array elements, sorting the array, copying the array, and querying elements in the array.

• 4.1 Traversing arrays

Traversing an array is the process of accessing all elements in the array, usually done using a loop.

Use  for a loop to iterate over the array:
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}
Use an enhanced  for-each loop to iterate over an array:
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}

• 4.2 Filling and replacing array elements

You can fill and replace elements in an array through a loop.

int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = i + 1; // 填充数组元素
}

• 4.3 Sorting arrays

Java provides several sorting algorithms to sort arrays, such as bubble sort, selection sort, and quick sort. Here is an example using the Arrays class to sort an array:

int[] numbers = {5, 2, 9, 1, 5};
Arrays.sort(numbers); // 对数组进行升序排序

• 4.4 Copying Arrays

Different methods can be used to copy one array to another array. Here is System.arraycopyan example of use:

int[] sourceArray = {1, 2, 3};
int[] targetArray = new int[sourceArray.length];
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

• 4.5 Query Array

You can use a loop to traverse the array to find a specific element, or use a search algorithm to find the location of an element. Here is an example of a linear search:

int[] numbers = {10, 20, 30, 40, 50};
int target = 30;
int index = -1;

for (int i = 0; i < numbers.length; i++) {
    if (numbers[i] == target) {
        index = i; // 找到目标元素的索引
        break;
    }
}

if (index != -1) {
    System.out.println("目标元素 " + target + " 在索引 " + index + " 处找到。");
} else {
    System.out.println("目标元素 " + target + " 未找到。");
}

5. Array arrangement algorithm

An array permutation algorithm is an algorithm used to rearrange the elements of an array in a specific order. In Java, there are multiple sorting algorithms to choose from, each with its own advantages and applicable scenarios.

• 5.1 Bubble sort

Bubble sort is a basic sorting algorithm that repeatedly iterates through an array, comparing two adjacent elements and swapping them as necessary until the entire array is sorted. Bubble sort is suitable for small data sets.

public static void bubbleSort(int[] arr) {
    int n = arr.length;
    boolean swapped;
    do {
        swapped = false;
        for (int i = 0; i < n - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                // 交换 arr[i] 和 arr[i+1] 的位置
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
}

• 5.2 Direct selection sorting

Direct selection sort is a simple sorting algorithm that selects the smallest (or largest) element in the unsorted part and places it at the end of the sorted part. Direct selection sort is suitable for small data sets.

public static void selectionSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        // 交换 arr[i] 和 arr[minIndex] 的位置
        int temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
}

• 5.3 Reverse sorting

Reverse sort is a simple sorting algorithm that reverses the order of array elements, i.e. swaps the first element with the last element, the second element with the second-to-last element, and so on.

public static void reverseSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n / 2; i++) {
        // 交换 arr[i] 和 arr[n-i-1] 的位置
        int temp = arr[i];
        arr[i] = arr[n - i - 1];
        arr[n - i - 1] = temp;
    }
}

6.Practice and exercises

• 6.1. Array overview

  • Exercise 1:  Create an integer array to store 5 of your favorite numbers and write code to print out those numbers.

• 2. One-dimensional array

  • Exercise 2:  Create an array of strings containing the names of some fruits, and then use a loop to loop through and print the names of the fruits in the array.
  • Exercise 3:  Write a program that accepts a set of numbers entered by the user and then calculates their average.

• 3. Two-dimensional array

  • Exercise 4:  Create a two-dimensional integer array to represent the initial state of a nine-square Sudoku game, and write code to print out the initial state of the Sudoku.
  • Exercise 5:  Write a program that generates a 3x3 random maze map that includes a starting point, an ending point, and walls.

• 4. Basic operations of arrays

  • Exercise 6:  Write a program that accepts a set of numbers entered by the user and finds the maximum and minimum values.
  • Exercise 7:  Create two integer arrays representing the coordinates of two vectors, and then write code to calculate the dot product (inner product) of these two vectors.

• 5. Array arrangement algorithm

  • Exercise 8:  Use bubble sort or selection sort to sort an integer array in ascending order and print the sorted array.
  • Exercise 9:  Write a program that generates an array of 10 random integers and sorts it using the quicksort algorithm.

• 6. Comprehensive practice

  • Exercise 10:  Create a simple task management program that uses arrays to store task descriptions and status (unfinished/completed) and provides options to add, view, and mark the status of tasks.

(The above are ten small questions, which will be answered in the next article)

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/132773358