Java knowledge point sorting: Chapter 3 loops, arrays, stacks, objects in java

9. Loop in java:

loop in java

for loop:

Generally used when the number of loops is clearly known

        ①            ②         ③

for( initialization expression ; boolean expression ; increment expression ) {

 

                 ④

// loop body

}

for(int i = 0 ; i<3;i++){

System.out.println(i);

}

10. Sorting of Java Arrays

 [8,2,3,7,1] --->[1,2,3,7,8]

Bubble Sort

selection sort

Insertion sort

........

 

Arrays.sort();

 

 

Bubble Sort

[8,2,3,7,1]

Each sorting will pick out the largest number in this sorting and put it at the back

Compare two adjacent elements , the larger one is backward, the smaller one is forward .

 

First sort:

   First comparison    8 <-> 2 [2,8,3,7,1]

   Second comparison    8 <-> 3 [2,3,8,7,1]

   Third comparison    8 <-> 7 [2,3,7,8,1]

   Fourth comparison    8 <-> 1 [2,3,7,1,8]

Second sort :

  First comparison     2 -> 3 [2,3,7,1,8]

  Second comparison     3 -> 7 [2,3,7,1,8]

  Third comparison     7 <-> 1 [2,3,1,7,8]

Third order :

  First comparison     2 -> 3 [2,3,1,7,8]

  Second comparison     3 <-> 1 [2,1,3,7,8]

fourth order 

  First comparison     2 <-> 1 [1,2,3,7,8]

 

There are a total of 5 numbers in the array :

How many times do you need to sort, and how many times for each sort to compare ?

 

At most arr.length-1 sorting is required

The first sort compares 4 times

The second sort compares 3 times

The third sort compares 2 times

The fourth sort compares 1 time

 

Code for bubble sort :

The outer for loop controls the number of times of sorting

The inner for loop controls the number of comparisons per sort

for(int i=0;i<arr.length-1;i++){

for(int j =0 ;j<arr.length-i-1;j++){

// Compare two by two, swap positions

if(arr[j] > arr[j+1]){

int temp = arr[j+1];

arr[j+1] = arr[j];

arr[j] = temp;

}

}

}

选择排序

将数组中的每个元素与第一个元素比较,

如果这个元素小于第一个元素,交换位置

 

每次排序找出一个最小的往前面放.

 

[8,2,3,7,1]

for(int i =0 ;i <arr.length-1;i++){

for(int j =i+1;j<arr.length;j++){

if(arr[i]>arr[j]){

  int temp = arr[i];

  arr[i] = arr[j];

  arr[j] = temp ;

}

 

}

}

 

 

 

11方法的递归调用(了解为主,掌握为辅)

  f(n){

f(n-1);

  }

 

y =f(n)=1+3+5+7+9+....+n  == f(n-2)+n ==f(n-4)+n-2+n

f(n) =1~n

f(n-2) =1~n-2

f(n-4) =1~n-4  

 

1 3 5 7 9.... n-4  n-2  n

 

计算 9+7+5+3+1

n = 9

f(n){

   1 +3+5+7+n

   f(n-2)+n;

}

f(n-2){

   f(n-4)+n-2;

}

 

f(1)  == 1

 

publicstatic int f(int n){

    if(n ==1){

return 1 ;

    }

    return f(n-2)+n;

}

f(9) =f(7)+9

f(7) =f(5)+7

f(5) =f(3)+5

f(3) =f(1)+3

f(1) =1

12.栈内存

栈是计算机中的一种数据存储方式,java进程启动时在内存中开辟的存储空间. 

栈内存遵循LIFO(后进先出).java中的所有局部变量在栈中分配空间

局部变量:

    写到方法中的变量

    方法的形参

当离开局部变量的作用域,变量被回收,从栈中删除.

           java中的方法调用就是使用栈实现的.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324770558&siteId=291194637