バブルと選択のソート
1920 ワード
/*
* function:bubble and selection sort
*
*/
public class Bubble$SelectionSort {
public static void main(String args[]) {
int a[] = { 12, 66, 2, 635, -6, 89, 0, 398, 1, 28, 56, 48, 8 };
int b[] = new int[a.length];
System.arraycopy(a, 0, b, 0, a.length);
System.out.println("before sort:");
printArray(a);
bubbleSort(a);
System.out.println();
System.out.println("after sort:");
printArray(a);
System.out.println();
System.out.println("before sort:");
printArray(b);
selectionSort(b);
System.out.println();
System.out.println("after sort:");
printArray(b);
}
private static void printArray(int[] arr){
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+"\t");
}
/*
* fuction:sort array
* name:bubble sort
* params:int[] arr
*/
private static void bubbleSort(int[] arr){
for (int i = 0; i < arr.length; i++) {
for (int j = 1; j < arr.length - i; j++) {
if (arr[j - 1] > arr[j]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
}
/*
* fuction:sort array
* name:selection sort
* params:int[] arr
*/
private static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[min] > arr[j])
min = j;
}
if (min != i) {
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}
}