标签:import list integer sel log turn i+1 复杂 highlight
选择排序,复杂度O(n²)
package com.example.demo; import org.junit.Test; /** * 选择排序 * @author zhzh.yin * */ public class HTest { @Test public void testMethod(){ Integer [] numList = {1,2,2,2,1,4,5,2,5,3,9,6}; for(int i=0;i<numList.length-1;i++){ int max = numList[i]; for(int j = i+1;j<numList.length;j++){ if(numList[i]<numList[j]){ max = numList[j]; numList[j]=numList[i]; numList[i]=max; } } } for(int num:numList){ System.out.print(numList[num]+" "); } } }
冒泡排序 复杂度 O(nlogn)
package com.example.demo; import org.junit.Test; /** * 冒泡排序 * @author zhzh.yin * */ public class FTest { @Test public void testMethod(){ Integer[]numList = {1,2,1,1,1,8,3,5,1}; if(numList.length==1){ System.out.println("-1"); }else if(numList.length==2){ String string =""; System.out.println( numList[1]>numList[2]? numList[1]+""+numList[0]:numList.toString());; } int temp = 0; for(int i =0;i<numList.length-1;i++){ for(int j=i+1;j<numList.length;j++){ if(numList[i]<numList[j]){ temp=numList[i]; numList[i]=numList[j]; numList[j]=temp; } } } for(int num :numList){ System.out.print(num+" "); } } }
二分法查询-非迭代
import org.junit.Test; /** * 找到数字N,适用于有多个重复数字,使用部分math原生方法向上取整/向下取整 * middle=min+(max-min)/2 算法更加准确
* 返回-1为没有找到 * @author zhzh.yin * */ public class CTest { @Test public void testMethod(){ Integer[] num ={1,2,3,3,3,4,5,5,5,5,5,6,6,6,7,10}; System.out.println("the num is at "+selectPosition(num,8)); } public int selectPosition(Integer [] numList,int num){ int min=0; int max=numList.length-1; int middle = -1; while(min<=max){ middle = min+(max-min)/2; System.out.println("min--"+min+",max--"+max+",middle--"+middle); if((min==middle||max==middle)&&numList[middle]!=num){ middle = -1; break; } if(numList[middle]<num){ min=(int) Math.floor(middle); }else if(numList[middle]>num){ max=(int) Math.ceil(middle); }else{ break; } } return middle; } }
标签:import list integer sel log turn i+1 复杂 highlight
原文地址:https://www.cnblogs.com/zhizhiyin/p/10986181.html