标签:
1冒泡排序和选择排序
1 package hello; 2 3 import java.io.BufferedOutputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileNotFoundException; 7 import java.io.FileOutputStream; 8 import java.io.IOException; 9 import java.io.InputStreamReader; 10 import java.io.OutputStreamWriter; 11 import java.text.SimpleDateFormat; 12 import java.util.Date; 13 import java.util.HashSet; 14 import java.util.Random; 15 import java.util.TreeSet; 16 17 public class Test02{ 18 public static void main(String[] args) throws Exception { 19 //把数组拼接成一个字符串 20 int[] arr={34,23,12,55,13}; 21 sort(arr); 22 System.out.println(arrayToString2(arr)); 23 for(int x=0;x<arr.length-1;x++){ 24 for(int y=0;y<arr.length-1-x;y++){ 25 if(arr[y]>arr[y+1]){ 26 int temp=arr[y]; 27 arr[y]=arr[y+1]; 28 arr[y+1]=temp; 29 } 30 } 31 } 32 System.out.println(arrayToString2(arr)); 33 34 } 35 36 public static void sort(int[] arr){ 37 for(int x=0;x<arr.length-1;x++){ 38 for(int y=x+1;y<arr.length;y++){ 39 if(arr[y]<arr[x]){ 40 int temp=arr[x]; 41 arr[x]=arr[y]; 42 arr[y]=temp; 43 } 44 } 45 } 46 } 47 public static String arrayToString2(int[] arr){ 48 StringBuffer sb=new StringBuffer(); 49 sb.append("["); 50 for(int i=0;i<arr.length;i++){ 51 if(i==arr.length-1){ 52 sb.append(arr[i]); 53 }else{ 54 sb.append(arr[i]).append(", "); 55 56 } 57 } 58 sb.append("]"); 59 return sb.toString(); 60 } 61 public static String arrayToString(int[] arr){ 62 String s=""; 63 s+="["; 64 for(int i=0;i<arr.length;i++){ 65 if(i==arr.length-1){ 66 s+=arr[i]; 67 }else{ 68 s+=arr[i]; 69 s+=", "; 70 } 71 } 72 s+="]"; 73 return s; 74 } 75 }
二分查找
1 package hello; 2 3 import java.io.BufferedOutputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileNotFoundException; 7 import java.io.FileOutputStream; 8 import java.io.IOException; 9 import java.io.InputStreamReader; 10 import java.io.OutputStreamWriter; 11 import java.text.SimpleDateFormat; 12 import java.util.Date; 13 import java.util.HashSet; 14 import java.util.Random; 15 import java.util.TreeSet; 16 17 public class Test02{ 18 public static void main(String[] args) throws Exception { 19 int[] arr={12,13,17,24,29,44}; 20 int mid=getIndex(arr, 14); 21 System.out.println(mid); 22 23 } 24 public static int getIndex(int[] arr,int value){ 25 int max=arr.length-1; 26 int min=0; 27 28 int mid=(max+min)/2; 29 30 while(arr[mid]!=value){ 31 if(arr[mid]>value){ 32 max=mid-1; 33 }else if(arr[mid]<value){ 34 min=mid+1; 35 } 36 if(min>max){ 37 return -1; 38 } 39 mid=(max+min)/2; 40 } 41 return mid; 42 } 43 }
标签:
原文地址:http://www.cnblogs.com/chengling/p/4776653.html