java实现二分法查找搜索、含选择排序法和冒泡排序

1、搜索都是建立在排好序的序列之上再搜索。
(1)二分法搜索
拿中间的数和要搜索的数比较。
(2)排序的顺序要求是升序。

package com.winney.countThree;

public class TestSearch {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        int[] in1 = {1,0,9,2,3,5,8,4,6,7,44,33};
        int[] in2 = {1,0,9,26,7,44,33};

        in1 = selectionSorted(in1);
        printArray(in1);
        in2 = bubbleSorted(in2);
        printArray(in2);
        System.out.println(binarySorted(44,in1));
        System.out.println(binarySorted(7,in2));
    }
    
    public static int[] selectionSorted(int[] in) {
        int k,temp;
        for(int i=0; i in[j]) {
                    k =j;
                }
            }
            if ( k != i) {
                temp = in[i];
                in[i] = in[k];
                in[k] = temp;
            }
        }
        return in;
    }
    
    public static int[] bubbleSorted(int[] in) {
        int temp;
        int  len = in.length;
        for(int i=len-1; i>=1; i--) {
            for(int j=0; j<=i-1; j++) {
                if( in[j] > in[j+1] ) {
                    temp = in[j];
                    in[j] = in[j+1];
                    in[j+1] = temp;
                }
            }
        }
        return in;
    }
    
    public static int binarySorted(int aim, int[] in) {
        int start = 0;
        int end = in.length-1;
        int m = end / 2;
        
        while(start <= end) {
            if ( aim == in[m] ) {
                return m;
            }
            if( aim > in[m] ) {
                start = m+1;
                m = (start + end)/2;
            }
            if( aim < in[m] ) {
                end = m-1;
                m = (start + end)/2;
            }
        }
        return -1;
    }
    
    public static void printArray(int[] in) {
        for(int i=0; i

2、日期对象的排序以及二分法搜索


class Date {
    private String today;
    int year,month,day;
    Date(int year, int month, int day) {
        this.year= year;
        this.month = month;
        this.day = day;
        today= year+"-"+month+"-"+day;
        //System.out.println("转换为日期是");
    }
    
    public String getToday() {
        return today;
    }
    
    public int compare(Date d) {
        return year > d.year ? 1
                : year < d.year ? -1
                :month > d.month ? 1
                : month < d.month ? -1
                :day > d.day ? 1
                :day < d.day? -1 : 0;
    }
    
    public static void printDates(Date[] dates) {
        for( int i=0; i

你可能感兴趣的:(java实现二分法查找搜索、含选择排序法和冒泡排序)