一些算法JAVA实现

在网上找了很多朋友的文章,总结一些常用的算法,用JAVA实现,把其记录下来:

冒泡排序:数列中,两个相邻的元素进行比较,如果顺序错误,就交换,以此类比较,一直比较到元素的最后一位。

public class maopao {

	public static void main(String args[]) {
		int[] values = { 3, 1, 6, 2, 9, 0, 7, 4, 5 };
		sort(values);
		for (int i = 0; i < values.length; i++) {// 排序后打印数组中的元素
			System.out.println("Index: " + i + "  value: " + values[i]);
		}
	}

	public static void sort(int[] values) {
		int temp;
		for (int i = 0; i < values.length; i++) {// 趟数
			for (int j = 0; j < values.length - i - 1; j++) {// 比较次数
				if (values[j] > values[j + 1]) {
					temp = values[j];
					values[j] = values[j + 1];
					values[j + 1] = temp;
				}
			}
		}
	}
}

二分查找:从是从中间向两边查找

package com.zyujie.common;

/**
 * 二分查找又称折半查找,它是一种效率较高的查找方法。   
 * 【二分查找要求】:1.必须采用顺序存储结构 2.必须按关键字大小有序排列。
 * @author Administrator
 * 
 */
public class BinarySearch {
	public static void main(String[] args) {
		int[] src = new int[] { 1, 3, 5, 7, 8, 9 };
		System.out.println(binarySearch(src, 3));
		System.out.println(binarySearch(src, 3, 0, src.length - 1));
	}

	/**
	 * * 二分查找算法 * *
	 * @param srcArray有序数组 *
	 * @param des查找元素 *
	 * @return des的数组下标,没找到返回-1
	 */
	public static int binarySearch(int[] srcArray, int des) {
		int low = 0;
		int high = srcArray.length - 1;
		while (low <= high) {
			int middle = (low + high) / 2;
			if (des == srcArray[middle]) {
				return middle;
			} else if (des < srcArray[middle]) {
				high = middle - 1;
			} else {
				low = middle + 1;
			}
		}
		return -1;
	}

	/**
	 * 二分查找特定整数在整型数组中的位置(递归)
	 * @param srcArray有序数组 *
	 * @param des查找元素 *
	 * 开始位置
	 * 结束位置
	 */
	public static int binarySearch(int[] dataset, int data, int beginIndex, int endIndex) {
		int midIndex = (beginIndex + endIndex) / 2;
		if (data < dataset[beginIndex] || data > dataset[endIndex] || beginIndex > endIndex) {
			return -1;
		}
		if (data < dataset[midIndex]) {
			return binarySearch(dataset, data, beginIndex, midIndex - 1);
		} else if (data > dataset[midIndex]) {
			return binarySearch(dataset, data, midIndex + 1, endIndex);
		} else {
			return midIndex;
		}
	}
}
这里写个单例模式:

public class Singleton {
  //私有的默认构造子
  private Singleton() {}
  //注意,这里没有final    
  private static Singleton single=null;
  //静态工厂方法 
  public static Singleton getInstance() {
       if (single == null) {  
           single = new Singleton();
       }  
      return single;
  }
}

递归:就是自身调用自身方法,见二分查找中的方法二。

暂时写到这里,如果后续有,再加上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值