一些算法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;
  }
}

遞歸:就是自身調用自身方法,見二分查找中的方法二。

暫時寫到這裏,如果後續有,再加上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章