import java.util.Scanner;
public class TestSearch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] array = createArray(100000);
int key = input.nextInt();
long startTime = System.nanoTime();
select(array);
//bubble(array);
//printArray(array);
System.out.println("\nThe place is " + binarySearch(array,key));
//System.out.println("\nThe place is " + linearSearch(array,key));
long endTime = System.nanoTime();
long execTime = endTime - startTime;
System.out.print(execTime);
input.close();
}
public static int[] createArray(int length) {
int[] array = new int[length];
for(int i = 0; i < length; i++) {
array[i] = (int)(Math.random()*100);
}
return array;
}
public static void printArray(int[] array) {
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void select(int[] array) {
int i,j;
for(i = 0; i < array.length - 1; i++) {
int min = array[i], minindex = i;
for(j = i + 1; j <= array.length - 1; j++) {
if(array[j] < min) {
min = array[j];
minindex = j;
}
}
if(minindex != i) {
array[minindex] = array[i];
array[i] = min;
}
}
}
public static void bubble(int[] array) {
for(int i = 0; i < array.length - 1; i++) {
for(int j = 0; j < array.length - 1 - i; j++){
if(array[j] > array[j+1]) {
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
public static int binarySearch(int[] array, int key) {
int low = 0, high = array.length - 1, mid = (low + high) / 2;
for(; high >= low;) {
if(key < array[mid]) {
high = mid - 1;
mid = (low + high) / 2;
}
else if(key > array[mid]) {
low = mid + 1;
mid = (low + high) / 2;
}
else {
return mid;
}
}
return -low - 1;
}
public static int linearSearch(int[] array, int key) {
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
return i;
}
return -1;
}
}
选择花费时间:纳秒
冒泡花费时间: