案例:输入一个字符串,统计每个字符出现的次数。
public class CountDemo { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("请输入字符串:"); String str = s.nextLine(); Map<Character,Integer> res = new HashMap<>(); for (int i = 0; i < str.length(); i++) { if (res.containsKey(str.charAt(i))){ res.put(str.charAt(i),res.get(str.charAt(i)) + 1); } else { res.put(str.charAt(i),1); } } System.out.println(res); } }
二分查找:
public class HalfSearch { public static void main(String[] args) { int[] nums = new int[]{21,22,32,35,38,54,64,94,99,500}; int index = halfSearch(nums, 54); System.out.println(index); } private static int halfSearch(int[] nums,int num) { int start = 0; int end = nums.length; while (start <= end){ int middleIndex = (start+end)/2; if (num < nums[middleIndex]){ end = middleIndex - 1; }else if (num > nums[middleIndex]){ start = middleIndex + 1; }else { return middleIndex; } } return -1; } }
冒泡排序:
public class Bubbling { public static void main(String[] args) { int[] nums = new int[]{12,15,61,13,41,95,24,65,5,44}; for (int i = 0; i < nums.length-1; i++){ for (int j = 0; j < nums.length-i-1; j++) { if (nums[j]>nums[j+1]){ int temp = nums[j]; nums[j] = nums[j+1]; nums[j+1] = temp; } } } System.out.println(Arrays.toString(nums)); } }
选择排序:
public class Selection { public static void main(String[] args) { int[] nums = new int[]{12,15,61,13,41,95,24,65,5,44}; for (int i = 0; i < nums.length-1; i++) { for (int j = i+1; j < nums.length; j++) { if (nums[j]<nums[i]){ int current = nums[j]; nums[j] = nums[i]; nums[i] = current; } } } System.out.println(Arrays.toString(nums)); } }