Java查找排序整理参考

Java查找排序整理参考

顺序查找

public static int sxchazhao(int [] array,int target)
{
        int res = -1;
        for(int i=0;i<array.length;i++)
        {
            if(array[i]==target)
            {
                res = i;
                break;
            }
        }
        return res;
}

二分查找

public static int erfenchazhao(int[] array,int target)
{
    int begin =0;
    int end = array.length-1;
    int res = -1;
    while (begin<=end)
    {
        int indexOfMid=begin+((end-begin)/2);
        //int indexOfMid=(begin+end)/2;
        int mid = array[indexOfMid];
        if(target>mid)
        {
            begin=indexOfMid+1;
        }
       else if(target<mid)
        {
            end=indexOfMid-1;
        }
        else {
            return res = indexOfMid;
        }
    }
    return  -1;
}

冒泡排序

public static void mppaixu(int [] array)
{
    int temp;
    for(int i = array.length-1;i>=0;i--)
    {
        for(int j =0;j<i;j++)
            if(array[j]>array[j+1])
            {
                temp=array[j];
                array[j]=array[j+1];
                array[j+1]=temp;
            }
    }
}

选择排序

public static void xuanzepx(int [] array)
{
    int i;
    int j;
    int temp;
    for(i=array.length-1;i>=0;i--)
    {
        //在当前选择一个最大的,联想天花板
        int xiabiao = 0;
        int max = array[0];
        for(j=0;j<=i;j++)
        {
            if(array[j]>max)
            {
                xiabiao = j;
                max = array[j];
            }
        }
        temp=array[xiabiao];
        array[xiabiao]=array[i];
        array[i]=temp;
    }
}

插入排序

public static void charupx(int [] array)
{
	//联想摸牌
    for(int i =0;i<array.length;i++)
    {
        int lastIndex = i-1;//手上的牌最后一个
        int xin= array[i];//新牌
        while(lastIndex>-1&&xin<array[lastIndex])
        {
            array[lastIndex+1]=array[lastIndex];
            lastIndex--;
        }
        array[lastIndex+1]=xin;
    }
}