標準バブルソート、Bubblesort

1535 ワード

package com.tnt.sortingalgorithm;

/**
 *  
 * 
 * @author FrankcoLuo
 * 
 */
public class Bubblesort {
	public void bubbleSortFunc1(int[] arr, int length) {
		int i = length, j;
		int temp;

		while (i > 0) {
			for (j = 0; j < i - 1; j++) {
				if (arr[j] > arr[j + 1]) {
					temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
			i--;
		}

	}

	/**
	 *  
	 * 
	 * @param arr
	 * @param length
	 */
	public void bubbleSortFunc2(int[] arr, int length) {
		//  
		int exchange = length - 1;

		while (exchange > 0) {
			//  
			int bound = exchange;

			//  
			exchange = 0;

			for (int i = 0; i < bound; i++) {
				if (arr[i] > arr[i + 1]) {
					//  
					int temp = arr[i];
					arr[i] = arr[i + 1];
					arr[i + 1] = temp;

					exchange = i + 1;
				}
			}
		}
	}

	public static void main(String[] args) {

		int[] arr = { 234, 264, 34, 358, 2, 4, 6, 54, 14, 25, 5, 24646, 2, 5, 5 };

		// 
//		new Bubblesort().bubbleSortFunc1(arr, arr.length);
		
		// 
		new Bubblesort().bubbleSortFunc2(arr, arr.length);

		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
	}
}