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.length; i++) {
k = i;
for(int j=i+1; j<in.length; j++) {
if (in[k] > 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<in.length; i++) {
System.out.print(" " + in[i]);
}
System.out.println();
}
}
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<dates.length; i++) {
System.out.print(dates[i].today+" ");
}
System.out.println();
}
public static Date[] dateSorted(Date[] dates) {
int k;
Date temp;
int len = dates.length;
for ( int i=0; i<len; i++) {
k = i;
for (int j=i+1; j<len; j++) {
if (dates[k].compare(dates[j]) == 1 ) {
k = j;
}
}
if (k != i) {
temp = dates[i];
dates[i] = dates[k];
dates[k] = temp;
}
}
return dates;
}
public static int binarySearchDate(Date[] dates, Date d) {
int start = 0;
int end = dates.length -1;
int m;
while (start <= end) {
m = (start + end) / 2;
if (d.compare(dates[m]) == 0) {
return m;
}
else if (d.compare(dates[m]) == 1) {
start = m+1;
}
else if (d.compare(dates[m]) == -1) {
end = m-1;
}
m = start + end;
}
return -1;
}
}
public class TestArrayDate {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Date[] dates;
dates = new Date[6];
int j=100;
for(int i=0; i<6; i++) {
dates[i] = new Date(1+i,2+i,3+i);
if( i%2 == 0) {
dates[i] = new Date(j+i,j+2,j);
}
}
Date d = new Date(100,102,100);
Date.printDates(dates);
Date.dateSorted(dates);
Date.printDates(dates);
int result = Date.binarySearchDate(dates,d);
System.out.print(result);
}
}