Java三种常见的排序算法:冒泡,选择,插入

/**
 * 
 * @author Administrator:阿福([email protected])
 *
 */
public class BubbleSorting {
	public static void main(String args[]) {
		
		//-------------------------冒泡排序
		// 最初的数组.
		int[] list = { 1, 5, 4, 2, 3, 8, 9, 7, 6, 12 };

		// 显示最初的数组.
		System.out.println("测试:冒泡排序——最初数组:");
		for (int i = 0; i < list.length; i++) {
			System.out.print("  " + list[i]);
		}
		bubbleSort(list);
		System.out.println();

		// 输出排序后的数组.
		System.out.println("冒泡排序后的数组是:");
		for (int i = 0; i < list.length; i++){
			System.out.print("  " + list[i]);
		}
		System.out.println();System.out.println();System.out.println();
		
		//------------------------选择排序
		
		// 显示最初的数组.
		int[] lists = { 1, 5, 4, 2, 3, 8, 9, 7, 6, 12 };
		System.out.println("测试:选择排序——最初数组:");
		for (int i = 0; i < list.length; i++) {
			System.out.print("  " + lists[i]);
		}
		Sectc(lists);
		System.out.println();

		// 输出排序后的数组.
		System.out.println("选择排序后的数组是:");
		for (int i = 0; i < list.length; i++){
			System.out.print("  " + lists[i]);
		}
		System.out.println();System.out.println();System.out.println();
		
		//------------------------插入排序
		// 显示最初的数组.
		Comparable[] b = {6,3,1,8,22,34,2,12,15,7,99,11};  
		System.out.println("测试:插入排序——最初数组:");
		for (int i = 0; i < b.length; i++) {
			System.out.print("  " + b[i]);
		}
		 insertSort(b);  
		System.out.println();

		// 输出排序后的数组.
		System.out.println("选择排序后的数组是:");
		for (int i = 0; i < b.length; i++){
			System.out.print("  " + b[i]);
		}
		System.out.println();System.out.println();System.out.println();
	
		 
		        
		         
	}

	/**
	 * 选择排序
	 * 
	 * @param list
	 */
	static void Sectc(int[] list) {
		for (int i = 0; i < list.length; i++) {
			for (int j = 1 + i; j < list.length; j++)
				if (list[i] < list[j]) {
					int temp;
					temp = list[j];
					list[j] = list[i];
					list[i] = temp;

				}

		}

	}
	/**
	 * 冒泡排序
	 * @param list
	 */
	static void bubbleSort(int[] list) {
		for (int i = 0; i < list.length; i++) {
			boolean flag = true;
			int temp = 0;

			for (int j = 1; j < list.length - i; j++)
				if (list[j - 1] < list[j]) {
					temp = list[j - 1];
					list[j - 1] = list[j];
					list[j] = temp;
					flag = false;
				}

			if (flag)
				break;
		}

	}

	/**
	 * 插入排序
	 * @param data
	 */
	public static void insertSort(Comparable[] data) {
		int j;
		for (int p = 1; p < data.length; p++) {
			Comparable key = data[p];
			for (j = p; j > 0 && (key.compareTo(data[j - 1]) < 0); j--)
				data[j] = data[j - 1];
			data[j] = key;
		}
	}
}
 

 

运行效果:
Java三种常见的排序算法:冒泡,选择,插入

你可能感兴趣的:(java,算法,J#)