插入排序
package tp.zgz.chapter04;
public class InsertSort {
public static void main(String[] args) {
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (100 + Math.random() * (100 + 1));
}
System.out.printf("排序前的數組:");
for (int i = 0; i < 10; i++) {
System.out.printf(arr[i] + " ");
}
System.out.println();
System.out.printf("排序後的數組:");
SelectedSort.Sort(arr);
}
static void Sort(int arr[]) {
//遍歷數據
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int j = i - 1; //j是要插入的位置
while (j >= 0 && temp < arr[j]) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
print(arr);
}
static void print(int arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.printf("%d ", arr[i]);
}
}
}