ITeye博客

好久不写算法,学习积累中!

txf2004 · 2013-01-29 15:39 · Markdown

public class SortAndSearch {
	static int[] x = {1,5,3,8,6};
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		bubbleSort(x);
		for(int i=0;i<x.length;i++){
			//System.out.println(i>>2);
		}
		int pos = binarySearch(x,6);
		System.out.println(pos);

	}
	//冒泡排序
	public static void bubbleSort(int[] x){
       for(int i=0;i<x.length-1;i++){
    	   for(int j=i+1;j<x.length;j++){
    		   if(x[i]>x[j]){
    			   swap(i,j);
    		   }
    	   }
       }
		
	}
	

	//交换数组两个位置的值
	public static void swap(int i,int j){
		
		int temp = x[i];
		x[i]=x[j];
		x[j]=temp;
		
	}
	//二分查找
	public static int binarySearch(int[] x,int target){
		int low = 0;
		int high = x.length-1;
		    while(low<=high){
		    int mid = low+(high-low)/2;
		    if(x[mid]==target){
			    return mid;
		    }else if(x[mid]<target){
			    low = mid+1;
		    }else{
			    high=mid-1;
		    }
		}
		return -1;
	}

}

代码比较简单,就不做过多注释

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。