常用的算法

来源:互联网 发布:java实现微信公众号 编辑:程序博客网 时间:2024/05/22 08:16

二分法查找需要先排序

public class Erfangfa {    //二方法查找是折半查找,优点是比较次数少   确定是待查表示有序的,    public static void main(String[] args) {        int [] num={90,35,40,53,50,18,23,80};        Arrays.sort(num);//排序        System.out.println(binarySearch(num, 30));    }    public static int binarySearch(int [] nums,int key){        int satart=0; //开始位置        int end=nums.length;        int mid=-1; //下标        while(satart<=end){            mid=(satart+end)/2;//3            System.out.println(mid);            if(nums[mid]==key){                  return mid;            }else if(nums[mid]<key){                satart=mid+1;            }else if(nums[mid]>key){                end=mid-1;            }        }        return -1;    }}

冒泡排序

public class 冒泡 {    public static void main(String[] args) {        int a[] = { 5, 50, 23, 25, 12, 36, 45 };        int temp;        for (int i = 0; i < a.length; i++) {            for (int j = i + 1; j < a.length; j++) {                if (a[i] > a[j]) {                    temp = a[i];                    a[i] = a[j];                    a[j] = temp;                }            }        }        for (int i = 0; i < a.length; i++)            System.out.println(a[i]);    }}
0 0