java常见算法

来源:互联网 发布:什么是嵌入式软件开发 编辑:程序博客网 时间:2024/05/24 03:20

1.冒泡排序
public int[] bubbleSort(int arr){int temp;boolean isOk;for(int i = 0; i < arr.length; i++){isOk = true;for(int j = 0; j < arr.length - i - 1; j++){   if(arr[j] > arr[j + 1]){   temp = arr[j];   arr[j] = arr[j + 1];   arr[j + 1] = temp;   isOk = false;   } }if(isOk){break;}}return arr;}
2.阶乘
public int calculatorJ(int j){return j == 1 ? 1 : j * calculatorJ(j - 1);}
3.最大公约数
public int divisor(int m, int n){if(m % n == 0)return n;else   return divisor(n, m % n);}
4.最小公倍数
public int getGBS(int n1, int n2){int gbs = n1 * n2 / divisor(n1,n2);return gbs;}
5.验证字符串是否符合由(),[],{}组成的不交叉表达式
public boolean metchBreaker(String s){List<Character> list = new LinkedList<Character>();char c;try{for(int i = 0; i < s.length(); i++){c = s.charAt(i);switch (c){case '{':case '[':case '(':list.add(c);break;case '}':if('{' == list.get(list.size() - 1)){list.remove(list.size() - 1);}else{return false;}break;case ']':if('[' == list.get(list.size() - 1)){list.remove(list.size() - 1);}else{return false;}break;case ')':if('(' == list.get(list.size() - 1)){list.remove(list.size() - 1);}else{return false;}break;}}}catch (Exception e) {return false;}if(list.isEmpty())return true;elsereturn false;}

原创粉丝点击