递归排序 冒泡排序 求子集
//10以内把所有能被2整除的数想乘 //递归(定义:自己调用自己) function ceng(val){ if(val == 1){ console.log(val); return 1; } if(val%2 !== 0){ return ceng(val-1); } return val * ceng(val-1); /*var n = 1; for(var i=1;i<=val;i++){ if(i % 2 == 0){ n = n * i; } } return n;*/ } var zhi = ceng(10); console.log(zhi);
//js自带的排序 var ary = [4,3,5,2,1]; ary.sort(function(a,b){ return a-b;//由小到大 return b-a;//由大到小 });
//冒泡排序,前后项相互比较 function sorts(ary){ var falge = false;//标识是否排好序了 var temp = null;//第三方变量 for(var i=0;i<ary.length-1;i++){// i -> 循环比较的轮数 for(var j=0;j<ary.leng-1-i;j++;){// j -> 每一轮比较的次数 if(ary[j] > ary[j+1]){//当前项大于后一项->交互位置 temp = ary[j]; ary[j] = ary[j+1]; ary[j+1] = temp; falge = true; } } if(falge == true){ break; } } return ary; } var ary = [4,3,5,2,1]; sort(ary);
//求数组子集 public static void main(String[] args) { String[] str = {"a","b","c","d"}; List<String> str1 = new ArrayList<String>(); List<String> str2 = new ArrayList<String>(); for(int s=0;s<str.length;s++) { str1.add(str[s]); } getStr1(0, str1, str2);//递归求子集 } public static void getStr1(int s,List<String> Liststr1,List<String> Liststr2) { if(s>Liststr1.size()-1) { if(Liststr2.size()<=0) { System.out.print("@");//爲空 }else { System.out.print(Liststr2.get(0)); for(int i=1;i<Liststr2.size();i++) { System.out.print(","+Liststr2.get(i)); } } System.out.println(); }else { Liststr2.add(Liststr1.get(s)); getStr1(s+1, Liststr1, Liststr2); int bstr = Liststr2.size(); Liststr2.remove(bstr-1); getStr1(s+1, Liststr1, Liststr2); } }