二分查找:
---缺点是必须为有序,如果是无序,可先排序---
package com.wjb.demo;
/**
* Created by wjb on 2017/5/10.
*/
public class SocketDemo {
public int binarySearch(int[] array,int key){
int left = 0;
int right = array.length-1;
while(left <= right){
int mid = (left + right) / 2;
if(array[mid] == key){
return mid;
}else if(array[mid] < key){
left = mid + 1;
}else{
right = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int i = new SocketDemo().binarySearch(new int[]{1,2,3,4,5},1);
System.out.println(i);
}
}
直接插入排序:
package com.wjb.demo;
/**
* Created by wjb on 2017/5/10.
*/
public class SocketDemo {
public void insertSort(int[] a) {
for (int i = 1; i < a.length; i++) {
if (a[i] < a[i - 1]) {
int j;
int x = a[i]; //x为待插入元素
a[i] = a[i - 1];
for (j = i - 1; j >= 0 && x < a[j]; j--) { //通过循环,逐个后移一位找到要插入的位置。
a[j + 1] = a[j];
}
a[j + 1] = x; //插入
}
}
}
public static void main(String[] args) {
int[] array = {1, 3, 2, 0, 5, 20, 10};
new SocketDemo().insertSort(array);
for(int i : array){
System.out.println(i);
}
}
}
冒泡排序:
---升序---
package com.wjb.demo;
/**
* Created by wjb on 2017/5/10.
*/
public class SocketDemo {
public void BubbleSort(int[] array) {
for(int i = 0;i < array.length;i++){
for(int j = 0;j < array.length - i - 1;j++){
if(array[j] > array[j+1]){
int temp = array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
}
public static void main(String[] args) {
int[] array = {1, 3, 2, 0, 5, 20, 10};
new SocketDemo().BubbleSort(array);
for(int i:array){
System.out.println(i);
}
}
}
裴波那契函数:
package demo;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by wjb on 2016/12/20.
*/
// f(0)=1; f(1)=2;
// f(n)=f(n-1)+f(n-2);
public class Test2 {
public static void main(String[] args) {
Date date = new Date();
long time1 = date.getTime();
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println("当前时间是:" + sd.format(date));
System.out.println(f2(10));
Date date2 = new Date();
long time = date2.getTime();
System.out.print("执行花了:"+(time-time1)+"毫秒");
}
public static int f(int n) {
if(n == 1 || n == 2) {
return n;
} else {
return f(n - 1) +f(n - 2);
}
}
public static long f2(int n){
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
for(int i =2;i<n;i++){
list.add(list.get(i-1)+list.get(i-2));
}
return list.get(n-1);
}
/* 速度最快的方法 */
public static long f3(int n){
Integer[] arr = new Integer[2];
arr[0]=1;
arr[1]=2;
for (int i = 2; i< n; i++){
arr[i%2] = arr[0] + arr[1];
}
return arr[(n-1)%2];
}
}