java算法例子_java算法小例子
作为一个程序员,有时候我觉得自己都不适合,因为自己数学不好,算法不好,脑子不够灵活。而对于算法,感觉就像是数学题,总觉得很难。以前上学,在班里总有几个什么都不好,但唯独数学很厉害,真气人!面对难题时,我只能求助,自己想破脑瓜子都想不出什么好的解决办法,都不知道怎么提高这方面的能力。只能慢慢学习了。
自己买了本算法的书,有空的时候就看看,写一写,总是收获的!下面是几个例子:
1.判断闰年
public class LeapYear {
public static int leapYear(int year) {
if ((year % 400 == 0) || (year % 100 != 0) && (year % 4 == 0)) {
return 1; //is leap year
} else {
return 0; //not a leap year
}
}
public static void main(String[] args) {
int year;
int count = 0;
System.out.println("2000年到3000年之间所有的闰年如下:");
for (year = 2000; year <= 3000; year++) {
if (leapYear(year) == 1) {
System.out.print(year + " ");
count++;
if (count % 16 == 0) {
System.out.println();
}
}
}
System.out.println("一共有" + count + "个闰年!");
}
}
2.水仙花数
public class NarcissusNum {
public static void narcissusNum(int n) {
long i,start,end,temp,num,sum;
int j;
start = (long) Math.pow(10, n - 1);
end = (long) (Math.pow(10, n) - 1);
for (i = start; i <= end; i++) {
temp = 0;
num = i;
sum = 0;
for (j = 0; j < n; j++) {
temp = num % 10;
sum = (long) (sum + Math.pow(temp, n));
num = (num - temp) / 10;
}
if (sum == i) {
System.out.printf("%d\n", i);
}
}
}
public static void main(String[] args) {
int n;
n = 3;
System.out.printf("列举%d位的水仙花数:\n", n);
narcissusNum(n);
System.out.println();
n = 4;
System.out.printf("列举%d位的水仙花数:\n", n);
narcissusNum(n);
System.out.printf("\n");
}
}
3.判断素数
public class IsPrime {
public static int isPrime(int a) {
for (int i = 2; i < a; i++) {
if (a % i == 0) {
return 0; //not prime number
}
}
return 1; //is a prime number
}
public static void main(String[] args) {
int i,n,count;
n = 1000;
count = 0;
System.out.println("列举1~1000之间所有的素数");
for (i = 1; i < 1000; i++) {
if (isPrime(i) == 1) {
System.out.printf("%7d", i);
count++;
if (count % 10 == 0) {
System.out.println();
}
}
}
System.out.println();
}
}
4. List去重
public static List removeByFor(List list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = list.size() - 1; j > i; j--) {
if (list.get(i).equals(list.get(j))) {
list.remove(j);
}
}
}
return list;
}
public static List removeBySet(List list) {
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
return list;
}
public static List removeDuplicateWithOrder(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object element = iterator.next();
if (set.add(element)) {
newList.add(element);
}
}
list.clear();
list.addAll(newList);
return list;
}
public static List removeByContain(List list) {
List tempList = new ArrayList();
for (int i = 0;i < list.size(); i++) {
if (!tempList.contains(list.get(i))) {
tempList.add(list.get(i));
}
}
return tempList;
}
5.Map与Bean相互转换
public static Object mapToObject(Map map, Class> beanClass) throws Exception {
if (map == null) {
return null;
}
ConvertUtils.register((aClass, o) -> {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
return simpleDateFormat.parse(o.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}, Date.class);
Object obj = beanClass.newInstance();
BeanUtils.populate(obj, map);
return obj;
}
public static Map objectToMap(Object obj) throws Exception {
return BeanUtils.describe(obj);
}
public static Map objectToMapTwo(Object obj) throws Exception {
if (obj == null) {
return Maps.newHashMap();
}
Map map = Maps.newHashMap();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
public static Object mapToObjectTwo(Map map, Class> beanClass) throws Exception {
if (map == null) {
return null;
}
Object obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}
6.排序
//插入
public static void insertSort(int[] a) {
int length = a.length;
for (int i = 1; i < length; i++) {
int insertNum = a[i];
int j = i - 1;
while (j >= 0 && a[j] > insertNum) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = insertNum;
}
}
//希尔
public static void sheelSort(int a[]) {
int length = a.length;
for (int gap = length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < length; i++) {
int insertNum = a[i];
int j = i - gap;
while (j >= 0 && a[j] > insertNum) {
a[j + gap] = a[j];
j -= gap;
}
a[j + gap] = insertNum;
}
}
}
//冒泡
public static void bubble(int[] a) {
int length = a.length;
int temp;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
//简单选择排序
public static void selectSort(int[] a) {
int length = a.length;
for (int i = 0; i < length; i++) {
//记录当前最小数和位置
int key = a[i];
int position = i;
for (int j = i + 1; j < length; j++) {
if (key > a[j]) {
key = a[j];
position = j;
}
}
//交换
a[position] = a[i];
a[i] = key;
}
}
//快速排序
public static void quickSort(int[] a, int start, int end) {
if (a == null || start >= end) return;
int key = a[start];
int i = start, j = end;
while (i < j) {
while (i < j && a[j] >= key) {
j--;
}
if (i < j) {
a[i++] = a[j];
}
while (i < j && a[i] <= key) {
i++;
}
if (i < j) {
a[j--] = a[i];
}
}
a[i] = key;
quickSort(a, start, i - 1);
quickSort(a, i + 1, end);
}
//基数排序
public static void radixSort(int[] a) {
int queueNum = 10;
int length = a.length;
//找到最大数,判断位数
int max = a[0];
for (int i = 1; i < length; i++) {
if (a[i] > max) {
max = a[i];
}
}
int times = 0;
while (max > 0) {
max /= 10;
times++;
}
//初始化10个队列
ArrayList queue = new ArrayList<>();
for (int i = 0; i < queueNum; i++) {
ArrayList queue1 = new ArrayList<>();
queue.add(queue1);
}
for (int i = 0; i < times; i++) {
//分配数组元素
for (int j = 0; j < length; j++) {
//得到位数
int x = a[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
ArrayList queue2 = queue.get(x);
queue2.add(a[j]);
queue.set(x, queue2);
}
//记录元素数
int count = 0;
//收集队列元素
for (int k = 0; k < queueNum; k++) {
while (queue.get(k).size() > 0) {
ArrayList queue3 = queue.get(k);
a[count] = queue3.get(0);
queue3.remove(0);
count++;
}
}
}
}
//堆排序
public static void heapSort(int[] a) {
int length = a.length;
for (int i = 0; i < length - 1; i++) {
adjustHeap(a, length - i - 1);
swap(a, 0, length - i - 1);
}
}
public static void adjustHeap(int[] a, int lastIndex) {
for (int i = (lastIndex - 1) / 2; i >= 0 ; i--) {
int k = i;
while (2*k + 1 <= lastIndex) {
int left = 2*k + 1;
if (left < lastIndex && a[left] < a[left + 1]) {
left++;
}
if (a[k] >= a[left]) break;
swap(a, k, left);
k = left;
}
}
System.out.println("调整后" + Arrays.toString(a));
}
//归并排序
public static void mergeSortTwo(int[] a, int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
mergeSortTwo(a, start, mid);
mergeSortTwo(a, mid + 1, end);
mergeTwo(a, start, mid, end);
}
}
public static void mergeTwo(int[] a, int start, int mid, int end) {
int[] temp = new int[a.length];
int p1 = start, p2 = mid + 1, k = start;
while (p1 <= mid && p2 <= end) {
if (a[p1] <= a[p2]) {
temp[k++] = a[p1++];
} else {
temp[k++] = a[p2++];
}
}
while (p1<=mid) {
temp[k++] = a[p1++];
}
while (p2<=end) {
temp[k++] = a[p2++];
}
for (int i = start; i <= end; i++) {
a[i] = temp[i];
}
}
java算法例子_java算法小例子相关推荐
- JAVA数据库应用的一个小例子
自己随便写的,以炉石为背景,写一个参考用的小例子,先上SQL表: if OBJECT_ID('card_pool') is not null drop table card_pool; create ...
- java多线程卖火车票_Java多线程小例子(三个窗口卖火车票)
class Ticket implements Runnable{ private int TicketNum = 100; //100张火车票 private boolean flag = true ...
- java递推_Java算法-递推算法思想
递推算法是常用的算法思想,在数学计算等方面有着广泛的应用.递推算法适合有着明显公式的规律场合. 一.递推算法基本思想 递推算法是一种理性思维模式的代表,其根据已有的数据和关系,逐步推导而得到结果.递推 ...
- java protobuf 例子_java使用protobuf例子
Protobuf版本:2.5.0 最近研究Hadoop时,发现Hadoop的RPC使用到了Protobuf这个东西,于是就了解了这个 Protobuf Protobuf是google的一种数据交互格式 ...
- java 兔子问题_Java算法之“兔子问题”
Java算法中的兔子问题,假设有一只兔子,从出生后的第三个月起每个月都生一只兔子,小兔子长到第三个月后每个月又能生一只兔子,假设兔子都不死,问每个月的兔子总数是多少? 在写代码之前先想明白算法,假设第 ...
- java try catch 例子_Java异常处理综合例子(try、catch、finally、throws、throw)
Java异常处理综合例子(try.catch.finally.throws.throw) 佟强 2009年11月4日 http://blog.csdn.net/microtong package cn ...
- java插入法排序_java算法之插入排序法
思想:插入排序法的思想就是从数组的第二个元素开始,将数组中的每一个元素按照规则插入到已排好序的数组中以达到排序的目的.一般情况下将数组的第一个元素作为启始元素,从第二个元素开始依次插入.由于要插入到的 ...
- Java解释XML文件的小例子
<?xml version="1.0" encoding="GBK"?> <addresslist><name>hemmin ...
- java最大最小距离算法缺点_java算法(蓝桥杯)- 算法提高 题目1 最大最小值
问题描述 给定 N个整数,请你找出这 N个数中最大的那个和最小的那个. 输入格式 第一行包含一个正整数 N .(1 ≤ N ≤ 10000). 第二行为 N 个用空格隔开的整数,每个数的绝对值不超过 ...
最新文章
- GT Transceiver的回环模式
- C语言中typedef的六种用法
- Break,Continue,Return 傻傻分不清楚
- Python3空字符串和len()函数
- ios 自动打包命令_【实践】iOS使用Jenkins实现自动化打包并上传蒲公英
- 迈克菲实验室:仅42%的网络安全专业人士使用共享威胁情报
- Oracle12c异常关闭后启动PDBORCL(ORA-01033)
- 解决 Windows Update 更新错误/无法创建还原点 代码 0x80246008
- 【django学习】request.POST与request.POST.get两者主要区别
- 重磅!清华这个决定冲上热搜!网友:不愧是清华…
- Java网络编程————UDP实现ThinkPad S5网络唤醒
- 计算机系统结构_计算机系统基础:总线结构知识笔记
- plsql连接mysql教程_plsql直连数据库教程
- 安卓编程入门 06 开始接触后台代码
- Cura切片3d打印设置
- Laravel项目部署到线上需要注意的一些问题
- 惊艳爆了,这是我见过的最美Redis客户端
- 栾锟数据科学与计算机学院,山东女子学院学生会第四届第一任干部名单
- DXO 做了哪些测试?
- 分页存储逻辑地址转物理地址
热门文章
- 在idea使用maven工程建立web项目时,启动Tomcat访问不到项目首页。
- Redis概述和基础
- LeetCode简单题之拼写单词
- k8s核心组件详细介绍教程(配超详细实例演示)
- TVM apps extension示例扩展库
- 编译器设计-有限自动机
- 计算机视觉多目标检测整合算法
- 2021年大数据Flink(三十三):​​​​​​​Table与SQL相关概念
- 微信小程序提示 出现脚本错误或者未正确调用 Page()
- AndroidManifest.xml