---
title: "好久不写算法，学习积累中！"
author: "txf2004"
date: "2013-01-29T15:39:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2013-02-02T20:37:32Z"
id: 1783903
url: "https://txf2004.iteye.com/blog/1783903"
---

```
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;
	}

}
```

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