目录
4.n元素幂集
5.插入排序
6.俄式乘法
4.n元素幂集
代码:
运行结果:
5.插入排序
代码:
import java.util.Arrays; /* * 应用插入排序对序列2,6,1,4,5,3,2进行排序 */ public class InsertSort { public static void main(String[] args) { int[] a = { 2, 6, 1, 4, 5, 3, 2 }; Insertsort(a); System.out.println(Arrays.toString(a)); } public static void Insertsort(int[] a) { int i, j; for (i = 1; i < a.length; i++) { int cur = a[i]; // 待比较值 for (j = i - 1; j >= 0 && a[j] > cur; j--) { a[j + 1] = a[j]; } a[j + 1] = cur; } } }
运行结果:
[1, 2, 2, 3, 4, 5, 6]
6.俄式乘法
代码:
import java.util.Scanner; public class RussianMultiplication { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入两个数字(回车符间隔)"); int n = sc.nextInt(); int m = sc.nextInt(); sc.close(); int res = Rmult(n, m); System.out.printf("%d * %d == %d", n, m, res); } public static int Rmult(int n, int m) { int sum = 0; while (n != 0) { if (n % 2 != 0) { n--; // 奇数情况 sum += m; } else { n >>= 1; m <<= 1; } } return sum; } }
运行结果:
请输入两个数字(回车符间隔)
50
65
50 * 65 == 3250