算法题
1 一维数组随机赋值,值各不相同
package com.okc.java;
public class ArrayAssignment {
public static void main(String[] args) {
//State a linear array that we output
int[] arrayForTest = new int[6];
//State a variable that give a assigned value to each the element of the array
int a1i ;
//loop in the array and assign every element
for (int i = 0 ; i < arrayForTest.length ; i++) {
boolean flag1 = false;
do {
//give a random number between 1 & 30
a1i = (int)(Math.random()* 30 + 1);
//identify that if this number equals to any element of the array
for (int j = 0 ;j< arrayForTest.length ;j++) {
if (a1i == arrayForTest[j]) {
flag1 = true ;
break;
}else {
flag1 = false ;
continue;
}
}
}while(flag1 == true);
arrayForTest[i] = a1i;
}
for(int i = 0 ;i < arrayForTest.length ; i++) {
System.out.println(arrayForTest[i]);
}
}
}
2.线性查找:equals方法
二分查找
3. 排序
冒泡排序:
- 易错点:i和j不分
- 难点:双层循环嵌套-- 每次遍历的长度会逐级递减
package com.okc.java;
public class BubbleSortTest {
public static void main(String[] args) {
int[] arr = new int[] {43,32,76,-98,0,64,33,-21,32,99} ; // len = 10
//Bubble Sort
for(int i= 0 ; i < arr.length -1;i++) {
for(int j = 0 ;j < arr.length -1 - i ;j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for(int o = 0 ;o< arr.length;o++) {
System.out.print(arr[o] + "\t");
}
}
}
其他题
1.while(布尔表达式)
- java没有从整数到布尔的隐式转换
2. 数据类型的转化
- 解析:
3.代码块构造器的执行顺序
- 解析:
B是入口
先静态先父类