常用算法

来源:互联网 发布:知乎女神阿子车 编辑:程序博客网 时间:2024/05/17 03:44

插入排序

public static void main(String[] args) {        int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35,                25, 53, 51 };        int temp = 0;        int j = 0;        for (int i = 1; i < a.length; i++) {            if (a[i] < a[i - 1]) {                temp = a[i];                for (j = i - 1; j >= 0 && a[j] > temp; j--) {                        a[j+1]=a[j];                }                a[j+1] = temp;            }        }        for(int k:a){            System.out.print(k+",");        }    }

冒泡排序

int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35,                25, 53, 51 };        for(int i=0;i<a.length-1;i++){            for(int j=i;j<a.length-i-1;j++){                if(a[j]>a[j+1]){                    int temp = a[j];                    a[j]=a[j+1];                    a[j+1] = temp;                }            }        }        for(int k:a){            System.out.print(k+",");        }    }

二分查找(循环)

public static void main(String[] args) {        int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35,                25, 53, 51 };        for(int i=0;i<a.length-1;i++){            for(int j=i;j<a.length-i-1;j++){                if(a[j]>a[j+1]){                    int temp = a[j];                    a[j]=a[j+1];                    a[j+1] = temp;                }            }        }        int low = 0;        int high = a.length-1;        while(low<=high){            int mid = (low+high)/2;            if(78==a[mid]){                System.out.print("数组位置:"+mid);                break;            }            else if(78<a[mid]){                high = mid-1;            }            else{                low = mid+1;            }        }    }

二分查找(递归)

private static int halfSearch(int[] a,int low,int high,int target){        if(low>high){            return -1;        }        else{            int mid = low+high;            if(target == a[mid]){                return mid;            }            else if(target < a[mid]){                return halfSearch(a,low,mid-1,target);            }else return halfSearch(a,mid+1,high,target);        }    }

数组倒序

public static void main(String[] args) {        int a[] = { 1,2,45,78,56,22};        for(int i =0;i<a.length/2;i++){            int k = a[i];            a[i]=a[a.length-i-1];            a[a.length-i-1]=k;          }
0 0
原创粉丝点击