程序输出:
作业二:要求采用二分法找出指定的数值并将其在数组的索引返回,如果没有找到则返回 -1
package org.westos.homework; /** * 现要求采用二分法找出指定的数值并将其在数组的索引返回,如果没有找到则返回 -1 */ import java.util.Arrays; public class HomeWork02 { public static int search(int[] arr,int key) { Arrays.sort(arr); //System.out.println(Arrays.toString(arr)); int start = 0; int end = arr.length-1; while(start <= end) { int middle = (start + end)/2; if(key < arr[middle]) { end = middle-1; }else if(key > arr[middle]) { start = middle+1; }else{ return middle; } } return -1; } public static void main(String[] args) { int [] arr = {80,40,50,45,90,120,30,20,100}; System.out.println(search(arr, 40)); System.out.println(search(arr, 30)); System.out.println(search(arr, 100)); } } 程序输出:2
1
7
作业三、统计大串中小串出现的次数:
package org.westos.homework; import java.util.Scanner; /** * 统计大串中小串出现的次数 * 举例:在字符串” woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun”中java出现了5次 * 分析:1)将字符串转化为字符数组。 * 2) * @author 代虎 * */ public class HomeWork03 { public static void countif(String BigStr,String str) { char[] userCh = BigStr.toCharArray(); char[] strCh = str.toCharArray(); int count = 0; //System.out.println("输入子串第1个元素"+strCh[0]); for(int i=0;i<userCh.length;i++) { //System.out.println("大串中第"+i+"个元素"+userCh[i]); if(strCh[0] == userCh[i]) { String temp = BigStr.substring(i, i+strCh.length); //System.out.println("temp======="+ temp); if(temp.equals(str)) { count++; }else{ //System.out.println("您所要找的小串在大串中不存在!"); } } } System.out.println("您所要找的小串在大串中共出现" + count + "次"); } public static void main(String[] args) { System.out.println("请您输入一段大的字符串"); Scanner sc = new Scanner(System.in); String BigStr = sc.next(); System.out.println("请输入您要查找的子串"); String str = sc.next(); countif(BigStr, str); } } 程序执行: