作业1
对10的成绩按照从低到高的顺序排列 三种方式
package day08;
public class Test01 {
public static void main(String[] args) {
int[] scores= {1,7,2,7,2,99,22,5,16,75,5};
// BubSort(scores);
// SelectSort(scores);
InsertSort(scores);
for(int i:scores) {
System.out.print(i+" ");
}
}
public static void InsertSort(int[] scores) {
for(int i=1;i<scores.length;i++) {
int index=i;
while(!(scores[index]>scores[index-1])) {
int temp=scores[index];
scores[index]=scores[index-1];
scores[index-1]=temp;
index--;
}
}
}
private static void SelectSort(int[] scores) {
for(int i=0;i<scores.length;i++) {
int k=i;
for(int j=i+1;j<scores.length;j++) {
if(scores[k]>scores[j]) {
k=j;
}
}
int temp=scores[i];
scores[i]=scores[k];
scores[k]=temp;
}
}
private static void BubSort(int[] scores) {
for(int i=0;i<scores.length;i++) {
for(int j=0;j<scores.length-1;j++) {
if(scores[j]>scores[j+1]) {
int temp=scores[j];
scores[j]=scores[j+1];
scores[j+1]=temp;
}
}
}
}
}
运行结果
作业2
某个人进入如下一个棋盘中,要求从左上角开始走, 最后从右下角出来(要求只能前进,不能后退), 问题:共有多少种走法?
0 0 0 0 0 0 0 00 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
package day08;
public class Test03 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int[][] arr=new int[5][9];
fun(arr);
}
private static void fun(int[][] arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
if(i==0||j==0) {
arr[i][j]=1;
}
}
}
for(int i=1;i<arr.length;i++) {
for(int j=1;j<arr[0].length;j++) {
arr[i][j]=arr[i][j-1]+arr[i-1][j];
}
}
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println(arr[arr.length-1][arr[0].length-1]);
}
}
运行结果
1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8 9
1 3 6 10 15 21 28 36 45
1 4 10 20 35 56 84 120 165
1 5 15 35 70 126 210 330 495
495
作业3
二分查找
package day08;
public class Test02 {
public static void main(String[] args) {
//二分查找
int[] scores= {1,7,2,7,2,99,22,5,16,75,5};
Test01.InsertSort(scores);
for(int i:scores) {
System.out.print(i+" ");
}
int s=0;
int e=scores.length-1;
int x=75;
while(true) {
int mid=(s+e)/2;
if(scores[mid]==x) {
System.out.println("\n"+mid);
break;
}else if(x<scores[mid]) {
e=mid-1;
}else if(x>scores[mid]) {
s=mid+1;
}
}
}
}
运行结果