# 6. Arrays and Sorting

Keywords: Java Algorithm array

Catalog

1. Array base

1.1. Introducing arrays

Initial Value and Creation of 1.2 Array

1.3 Array Practice

2. Array Expansion

2.1 Custom Array Expansion

2.2 System-defined Array Expansion Method

3. Method encapsulation in arrays

3.1 References on Methods

3.2 Variable parameters

Return value of 3.3 method returns array

4. Sorting

4.1 Sort Base

4.2 Bubble Sorting

4.3 Select Sort

4.4 Insert Sort

4.5 Sorting provided by the system

4.6 One-Dimensional Array Practice (Fibolacci Sequences)

5. Two-dimensional arrays

5.1 Basic Overview

Creation of a 5.2-dimensional array

Assignment and Value of 5.3 Two-Dimensional Array

Traversal of a 5.4 two-dimensional array

Exercise on 5.5 2-D Array (Yang Hui Triangle)

# 1. Array base

## 1.1. Introducing arrays

Introduction: Why use arrays?
Requirements: Please store the results of the whole class
Depending on the variable: int score1=66;   int score2=68;   int score3=77;...
Disadvantages: 60 students'results require 60 variables, which is too redundant
Assume that each student has a +1 score?   What to do?
Disadvantage: Every variable needs to do + 1 operation, which is not easy to manage
Introduce an array:
Concept: A contiguous set of memory spaces for storing elements of the same type
Array features: same type, fixed length

```===========================Case 1============================
public class ArrayTest1 {
public static void main(String[] args) {
//Requirements: Please store the results of the whole class
//Arrays are reference types: you often need to open up space before saving values
int[] arr = new int; //Array space defining three int types
//Assigning (storing) and taking a subscript range to an array element by subscripts: 0~Length-1
arr = 66;   //assignment
arr = 68;
arr = 77;
//Arr = 99; // ArrayIndexOutOfBoundsException: Array Boundary Exception
//Optimizing Print Output - Circular Printing (Traversal)
System.out.println("Array length:"+arr.length);  //3
for(int i=0;i<arr.length;i++) { //i=0
System.out.println(arr[i]);  //arr,arr..
}
//System.out.println(arr);  //ArrayIndexOutOfBoundsException

}
}
```
```===========================Case 2============================
//Case 2: Give each student a result of + 1
public class ArrayTest2 {
public static void main(String[] args) {
int[] arr = new int; //Array space defining three int types
//Assigning (storing) and taking a subscript range to an array element by subscripts: 0~Length-1
arr = 66;   //assignment
arr = 68;
arr = 77;
for(int i=0;i<arr.length;i++) {
arr[i] += 1; //arr[i]=arr[i]+1;

System.out.println(arr[i]);
}

}
}
```

## Initial Value and Creation of 1.2 Array

```=======================Initial value of array========================
//Initial value problem for arrays:
public class Test1 {
public static void main(String[] args) {
int[] a = new int;  //Create three spaces to store int values
System.out.println(a);  //0 int type initially 0

double[] b = new double;
System.out.println(b);  //Initial value of type 0.0 double

boolean[] c = new boolean;
System.out.println(c);  //false

char[] d = new char;
System.out.println(d);  //Characters with code value of 0

String[] e = new String;
System.out.println(e);  //String type is initially null
}
}
```
```=======================Array creation========================

//Array creation:
public class Test2 {
public static void main(String[] args) {
//---------------------------------------------------------------------
//1. Declare before creating space
int[] a;
a = new int;

//2. Create space while declaring - (common)
int[] c = new int;

//------------------ Static assignment (assignment with space) ---------------
//3. Assigning while creating space
int[] d = new int[]{1,3,5}; //The length of the array, determined by the number of values

//4. Assignment while creating space (simplified - common)
int[] e = {1,3,5};
}
}
```

## 1.3 Array Practice

```=======================Case 1========================
//Case 1: Given an integer array, count the average score of array elements
//Analysis: first iterate through all elements of the array; Sum again divided by length
public class Test1 {
public static void main(String[] args) {
int[] a = {68,75,83,63};
double sum = 0;  //Sum, initial 0
int len = a.length;
for(int i=0;i<len;i++) {
sum += a[i];
}
System.out.println("Average division of array elements:"+(sum/len));
}
}
```
```=======================Case 2========================
//Case 2: Given an array of integers, enter an integer n and output subscripts if it exists in the array; Otherwise Print-1
//For example: 7 3 8 2 6
//Input 1-1 Input 8 2
public class Test2 {
public static void main(String[] args) {
int[] a = {7,3,8,2,6};
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int index = -1;  //Record subscript
for(int i=0;i<a.length;i++) { //0
if(n==a[i]) {
index = i;  //If the match is up, come in and get the subscript
break;
}
}
System.out.println("Subscript:"+index);
}
}
```

# 2. Array Expansion

Array expansion:
As you can see from the previous array characteristics, the length of the array is fixed
If you need to expand the array, you need to recreate the space
The idea of expansion is to create a larger space than the original array and copy in the original array elements

## 2.1 Custom Array Expansion

```public class Test1 {
public static void main(String[] args) {
int[] src = {1,3,5};
int[] dest = new int[src.length+3];  //Define the target array, which has more space than the original
for(int i=0;i<src.length;i++) {
dest[i]=src[i];  //Loop assigns the original array element to the target array
}
for(int i=0;i<dest.length;i++) {
System.out.print(dest[i]+"\t");
}

//Assuming that we need to write our own implementation of array expansion, what are the parameters?
//copyOf1(); Source Array, Target Array, Source Location, Target Location, Copy Length
//copyOf2(); Source Array, Expanded Len gt h-->Return Expanded Array
}
}```

## 2.2 System-defined Array Expansion Method ```=================System Provided Extension Method Calls==================
public class Test2 {
public static void main(String[] args) {
int[] src = {1,3,5};  //Original Array

//-------Expansion mode 1---------
//int[] dest = new int[src.length+3]; // target array
//Parameter 1: Original Array 2. Original Start Position - Normally 0
//3. Target Array 4. Target Start Position - typically 0.5. Copy Length - typically the original Array Length
//System.arraycopy(src, 0, dest, 0, src.length);

//-----Expansion Mode 2-------
//Parameter 1: Original Array Parameter 2: Length Return Value to Expand: Expanded Target Array
int[] dest = Arrays.copyOf(src, src.length+3);

for(int i=0;i<dest.length;i++) {
System.out.print(dest[i]+"\t");
}

}
}```

# 3. Method encapsulation in arrays

## 3.1 References on Methods

```=====================Transfer Basic Type(pass by value)=====================

//Case: Variables are passed in as parameters through method calls, changing parameter values in method implementations;
//Print the variable in the main method to see if its value changes?
//Value transfer: A change in the parameter does not affect the argument
public class Test1 {
public static void main(String[] args) {
int a = 3;
change(a);
System.out.println("final result:"+a);  //3
}

private static void change(int a) {
a = 5;
}
}
``` ```=====================Pass-by reference type(Address Delivery)=====================
//Case 2: Passing an array as a parameter changes the elements of the array in the method implementation
//Print the array in the main method to see if it changes?
//Address Pass-Through: Changes in formal parameters affect arguments
public class Test2 {
public static void main(String[] args) {
int[] a = {1,3,5};
change(a);
System.out.println(a);  //9
}

private static void change(int[] a) {
a = 9;
}
}
``` ## 3.2 Variable parameters

```//Variable parameters:
//1. Evolve from the ordinary array parameters first
//Case: Print arrays by method encapsulation
//Variable parameter: Can receive variable argument format: int... a
public class Test3 {
public static void main(String[] args) {
//int[] a = {1,3,5};
//printArray(new int[]{1,3,5}); // Print Array

printArray(1,3,5);  //Essentially passed in a new array
}

//Variable Parameters - Essential: Arrays use decompile tools to view
private static void printArray(int...a) {
for(int i=0;i<a.length;i++) {
System.out.print(a[i]+"\t");
}
}
}
```

## Return value of 3.3 method returns array

```//Case: In the main method, an original array is passed in; Expand the original array in the method implementation;
//And returns the expanded array
public class Test1 {
public static void main(String[] args) {
int[] a = {1,3,5};
int[] b = copyOf(a,a.length+3);

//Array printing has been written out in the Arrays class:
//toString: Returns an array to a string
System.out.println(Arrays.toString(a));  //1,3,5

System.out.println(Arrays.toString(b));  //1,3,5,0,0,0
}

private static int[] copyOf(int[] a,int len) { //Enter the original array, and expand the length
//Create an expanded array
int[] b = new int[len];
//Loop the original array in an expanded array
for(int i=0;i<a.length;i++) {
b[i]=a[i];
}
return b;
}
}
```

# 4. Sorting

## 4.1 Sort Base

```=====================Sort Base======================
//Case 1: Exchange the values of two variables; For example: a=3,b=5 after exchange: a=5,b=3
//Analysis: Borrow a variable
public class SortBasic {
public static void main(String[] args) {
int a = 3;
int b = 5;
System.out.println("Before swap: a="+a+";b="+b);
//Note: Assignment, right as value, left as variable
int t = a; //t=3
a = b; //a=5
b = t; //b=3
System.out.println("After exchange: a="+a+";b="+b);
}
}
```

## 4.2 Bubble Sorting ```//Bubble sorting: two or two adjacent numbers are compared, large put to the right, after a round of comparison, the number on the right most is the maximum; Compare (length-1) wheels by analogy
public class MaoPao {
public static void main(String[] args) {
int[] a= {3,1,5,2,9,7,4,6};
for(int i=0;i<a.length-1;i++) {//Outer layer represents number of rounds
for(int j=0;j<a.length-1-i;j++) {//The inner layer represents the number of comparisons per round, decreasing in turn
if(a[j]>a[j+1]) {
int t=a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
//System.out.println("No"+(i+1)+ "Wheel:"+Arrays.toString(a));
}
System.out.println("After sorting:"+Arrays.toString(a));
}
}
```

## 4.3 Select Sort

How it works: For the first time, select the smallest (or largest) element from the data elements to be sorted, store it at the beginning of the sequence, then find the smallest (largest) element from the remaining unsorted elements, and place it at the end of the sorted sequence. And so on until all the data elements to be sorted have zero number. ```//Select Sort: Assume the first element is the smallest, then compare with the following elements; Determine that the first position element is the smallest after a comparison;
//       Assume that the second element is the smallest, then compare with the following elements, and so on. Total Compare (Length-1) Wheel
public class XuanXe {
public static void main(String[] args) {

int[] a = {3,1,5,2,9,7,6,4};

for(int i=0;i<a.length-1;i++) {   //Outer layer represents number of rounds
for(int j=1+i;j<a.length;j++) { //Memory represents the number of comparisons per round
if(a[i]>a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
//System.out.println("No"+(i+1)+ "Wheel:"+Arrays.toString(a));

}
System.out.println("After sorting:"+Arrays.toString(a));
}
}
```

## 4.4 Insert Sort ## 4.5 Sorting provided by the system

```======================Sorting provided by the system======================

//Sorting method provided by the system (implementation is written out and we just need to call it)
public class SystemSort {
public static void main(String[] args) {
int[] a = {3,1,5,2,6};
Arrays.sort(a);  //Ascending order provided by the system
System.out.println(Arrays.toString(a));

//Assuming that the system provides ascending ordering, we need descending ordering. What can we do?
//Analysis: End swap, length of swap/2 times
int len = a.length;
for(int i=0;i<len/2;i++) {
int t = a[i];
a[i] = a[len-1-i];
a[len-1-i]=t;
}
System.out.println("Descending order:"+Arrays.toString(a));
}
}
```

## 4.6 One-Dimensional Array Practice (Fibolacci Sequences)

```======================One-dimensional Array Practice(fibonacci sequence)======================
//Think: Previously used Fibolacci arrays, using arrays to manipulate:
//0  1  1  2  3   5  8  13 ...
//Rule: the first item is 0, the second item is 1, and the third item after is equal to the first + second item
//Analysis: Treat the Fibrocci sequence as an element of the array, cycle through it, and set rules
public class FeiBo {
public static void main(String[] args) {
System.out.print("Please enter the number of items:");
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();  //Number of items, equal to the length in the array
int[] a = new int[len];
for(int i=0;i<len;i++) {
if(i==0||i==1) {
a[i]=i;  //a=0;a=1;
}else {
a[i]=a[i-1]+a[i-2];  //Loop to assign values to array elements
}
}
System.out.println(Arrays.toString(a));
}
}
```

# 5. Two-dimensional arrays

## 5.1 Basic Overview

Two-dimensional array: A one-dimensional array of one-dimensional arrays, in which you can see that the elements in one-dimensional arrays are also one-dimensional arrays

## Creation of a 5.2-dimensional array

```======================Creation of a two-dimensional array======================
//Creation of a two-dimensional array:
public class Test3 {
public static void main(String[] args) {
//--Dynamic Assignment-----
//1. Declare before creating space
int[][] a;
a = new int;

//2. Create space while declaring (common)
int[][] b = new int;

//3. Give a row length while creating space
int[][] c = new int[];
c=new int[]{3,5,8};
c=new int[]{1,5,7};

//-- Static assignment-----
//4. Assigning while creating space
int[][] d = {{1,2,5},{4,6,8}};  //Two-dimensional array with two rows and three columns

//Note: The third and fourth columns can be specified irregularly (understand), and loop traversal is the same, for example, the following static assignment operations:
int[][] e = {{1,2,5},{4,6}};
for(int i=0;i<e.length;i++) {
for(int j=0;j<e[i].length;j++) {
System.out.print(e[i][j]+"\t");
}
System.out.println();  //Enter
}
}
}
```

## Assignment and Value of 5.3 Two-Dimensional Array

```======================Assignment and Value of Two-Dimensional Array======================
public class Test1 {
public static void main(String[] args) {
//Two-dimensional array operation: can be seen as row and column operation, the length is by row length and column length, the subscript is row subscript and column subscript
int[][] a = new int;  //2 is row length 3 is column length
//assignment
a = 4;  //2-D Array Assignment Row Subscript Range: 0~Row Length-1 Column Subscript Range: 0~Column Length-1
a = 2;
a = 6;
//a = 7; // Column Subscript Overflow
a = 8;
//Value
System.out.println(a+"--"+a+"--"+a);
System.out.println(a+"--"+a+"--"+a);
//System.out.println(a); // Line Subscript Overflow
//Note: The general arrangement of two-dimensional arrays is often artificially designed to arrange rows and columns for our convenience.
}
}
```

## Traversal of a 5.4 two-dimensional array

```======================Traversal of a two-dimensional array======================
//Cyclic traversal of two-dimensional arrays
public class Test2 {
public static void main(String[] args) {
//Two-dimensional array operation: can be seen as row and column operation, the length is by row length and column length, the subscript is row subscript and column subscript
int[][] a = new int;  //2 is row length 3 is column length
//assignment
a = 4;  //2-D Array Assignment Row Subscript Range: 0~Row Length-1 Column Subscript Range: 0~Column Length-1
a = 2;
a = 6;
//a = 7; // Column Subscript Overflow
a = 8;
//Loop traversal
for(int i=0;i<a.length;i++) {  //a.length: Line length
for(int j=0;j<a[i].length;j++) {  //Number of columns per row
System.out.print(a[i][j]+"\t");
}
System.out.println();  //Enter
}

}
}
```

## Exercise on 5.5 2-D Array (Yang Hui Triangle) ```//Yang Hui Triangle
public class Test1 {
public static void main(String[] args) {
System.out.print("Please enter the row of Yang Hui triangle:");
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int[][] a = new int[row][row];
for(int i=0;i<row;i++) {
for(int j=0;j<=i;j++) {
if(j==0||j==i) { //1 if the first column or row and column are equal
a[i][j]=1;
}else{ //Current Position Value = Previous Line Position + Previous Line Position
a[i][j]=a[i-1][j]+a[i-1][j-1];
}

System.out.print(a[i][j]+"\t");
}
System.out.println();  //Line Break
}
}
}
```

Posted by langer on Fri, 12 Nov 2021 10:15:32 -0800