`
jayzotion
  • 浏览: 47916 次
  • 性别: Icon_minigender_1
  • 来自: 森林之城
社区版块
存档分类
最新评论

几种排序java实现

    博客分类:
  • java
阅读更多
package com.wyh.anl;

public class TestSort{

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		int a[] = { 115, 0, 5, 2, 1, 8, 9, 7, 6, 78 };
		bublSort(a);
		for (int j : a) {
			System.out.print(j + "  ");
		}
	}

	// 插入排序
	public static void insertSort(int a[]) {
		for (int i = 1; i < a.length; i++) {
			int tmp = a[i];
			int j = i;

			while (j > 0) {
				if (tmp < a[j - 1]) {
					a[j] = a[j - 1];
				} else {
					break;
				}
				j--;
			}
			a[j] = tmp;
		}
	}

	// 选择排序
	public static void selectSort(int a[]) {
		for (int i = 0; i < a.length; i++) {
			int sel = i;
			int tmp = i;
			for (int j = i; j < a.length; j++) {
				if (a[tmp] > a[j]) {
					tmp = j;
				}
			}
			if (tmp != sel) {
				int awp = a[sel];
				a[sel] = a[tmp];
				a[tmp] = awp;
			}
		}
	}

	// 冒泡排序法
	public static void bublSort(int a[]) {
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a.length - i - 1; j++) {
				int tmp = 0;
				if (a[j] > a[j + 1]) {
					tmp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = tmp;
				}
			}
		}
	}

	// 归迸排序法
	public static void merageSort(int data[], int first, int n) {

		int n1 = 0;
		int n2 = 0;

		if (n > 1) {
			n1 = n / 2;
			n2 = n - n1;

			merageSort(data, first, n1);
			merageSort(data, first + n1, n2);

			merage(data, first, n1, n2);
		}
	}

	private static void merage(int data[], int first, int n1, int n2) {

		int tmp[] = new int[n1 + n2];

		int serN1 = 0;
		int serN2 = 0;
		int serTmp = 0;

		while (serN1 < n1 && serN2 < n2) {

			if (data[first + serN1] < data[first + serN2 + n1]) {

				tmp[serTmp++] = data[first + (serN1++)];

			} else {

				tmp[serTmp++] = data[first + n1 + (serN2++)];
			}
		}

		while (serN1 < n1) {
			tmp[serTmp++] = data[first + (serN1++)];
		}

		while (serN2 < n2) {
			tmp[serTmp++] = data[first + n1 + (serN2++)];
		}

		for (int i = 0; i < (n1 + n2); i++) {
			data[first + i] = tmp[i];
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics