java 中常见的几种算法,解释很详细

来源:互联网 发布:淘宝宝贝导出excel 编辑:程序博客网 时间:2024/06/06 02:14

今天被同事问起了java中常见的几种算法,下面我就列举下常见的几种算法,希望能帮助大家,最后一种的字符串比较大家还是要注意下,这面还是不怎么容易理解的

class FindClass{

public static void main(String[] args){    int[] arr = {1,2,3,7,9,4,6,7,3};    // int[] arr = {1,2,3,5,7,9,};    // systemOP(arr);    // bubbleSort(arr);    // systemOP(arr);    //systemOP_2(getMax_1(arr));   String a = "nihaohelloworldohhh";   String b = "ghelloworldb";   systemOP_3(getMaxSubString(b,a));}

/** 折中查找 这里必须是一个有序素组 如果返回值时-1时,说明key值不存在
这里面还可以衍生出插入的方法,只要返回值更改为min即可,min返回值就是key值插入的角标
*/

public static int halfSearch(int[] arr,int key){    int min,max,mid;    min = 0;    max = arr.length-1;    while(min <= max){        mid = (max -min)/2;        if(key > arr[mid]){            min = mid + 1;        }else if (key < arr[mid]) {            max = mid -1;        }else{            return mid;        }    }    return -1;}/** 冒泡排序    什么叫做是冒泡排序 冒泡排序就是相邻的元素进行对比 一步一步的把最大值找出来,这就是冒泡排序    可以进行从大到小,也可以从小到大排序 只要更改switchSort 中的a<b即可*/public static void bubbleSort (int[] arr){    for (int x = 0; x<arr.length -1;x++) {        for (int y= 0; y<arr.length-x -1; y++) {    //-x表示每次对比的次数减少,-1表示避免角标越界            switchSort(arr,y,y+1);        }    }}// 获取最值 第一种public static int getMax_1(int[] arr){    int max = arr[0];    for (int x = 1;x<arr.length;x++) {        if (max < arr[x]) {            max = arr[x];        }    }    return max;}// 获取最值 第二种public static int getMax_2(int[] arr){    int max = 0;    for (int x = 1;x < arr.length; x++) {        if (arr[max] < arr[x]) {            max = x;        }    }    return arr[max];}// 选择排序 就是通过数组的一个元素和数组中所有的元素去比较,首先获取的是最小值,这里和冒泡排序的区别// 希望大家留意下排序的区别public static void selectSort(int[] arr){    for (int x = 0;x< arr.length -1;x++) {//这里减1是代表着最后一个元素不用去比较        for(int y=x +1;y < arr.length;y++) {            switchSort(arr,x,y);        }    }}public static void switchSort(int[] arr,int a,int b){    if(arr[a] > arr[b]){        int temp = arr[a];        arr[a] = arr[b];        arr[b] = temp;    }}public static void systemOP(int[] a){    System.out.print("[");    for (int x = 0; x < a.length; x++) {        if (x!=a.length-1) {            System.out.print(a[x]+",");        }else            System.out.println(a[x]+"]");    }}public static void systemOP_2(int a){    System.out.println("a::"+a);}public static void systemOP_3(String temp){    System.out.println("temp::"+temp);}//这是比较两个字符串的最大字字符串,思路是从最小的开始比较,这样会更快一点public static String getMaxSubString(String a,String b){    //max min  这里面是表示确保max:表示最大长度,min:表示最小长度    String max = "";String min = "";    max = (a.length()>b.length()?a:b);    min = max == a?b:a;    //一层循环是表示最短字符串从最大长度到慢慢变小    for(int x = 0;x<min.length();x++){        //这一层循环表示的是,从最大到最小的字符串,每一种要循环多少次        for (int y = 0,z = min.length() -x; z != min.length()+1;y++,z++ ) {            String temp = min.substring(y,z);            if(max.contains(temp)){                return temp;            }        }    }    return "";}

}

0 0
原创粉丝点击