選択、バブル、挿入ソート

1868 ワード

package com.companyname;

public class Sort {
	public static void main(String[] args) {
		int[] arr = new int[] { 41, 56, 11, 86, 22, 37, 8, 91, 19, 51, 94, 69,71, 48 };
		System.out.println(" :");
		printArr(arr);
//		bubbleSort(arr);
		insertSort(arr);
		System.out.println(" :");
		printArr(arr);
	}

	public static void selectSort(int[] arr) {   // 
		for (int i = 0; i < arr.length; i++) {
			for (int j = i + 1; j < arr.length; j++) {
				if (arr[i] > arr[j]) {
					int temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}
			}
			System.out.println(" " + i + " :");
			printArr(arr);
		}
	}

	public static void bubbleSort(int[] arr) {   // 
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr.length - 1; j++) {
				if (arr[j] > arr[j + 1]) {
					int temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
			System.out.println(" " + (i + 1) + " :");
			printArr(arr);
		}
	}

	public static void insertSort(int[] arr) {    // 
		for (int i = 1; i < arr.length; i++) {
			int temp = arr[i];
			int j = i;
			while (j > 0 && arr[j - 1] > temp) {
				arr[j] = arr[--j];
			}
			arr[j] = temp;
		}

	}

	public static void printArr(int[] arr) {
		System.out.print("[");
		for (int i = 0; i < arr.length; i++) {
			if (i == arr.length - 1) {
				System.out.println(arr[i] + "]");
			} else {
				System.out.print(arr[i] + ",");
			}
		}
	}
}