一、插入排序的介绍
- 数组分为排好序的部分和没排序的部分,排好序的部分放在前面。
- 每i躺选第i个元素放到排好序的部分所对应的位置。
二、Java实现
public class InsertSelect {
public int[] sort(int[] arr) {
for (int i = 1; i < arr.length; i++) {//每一趟
for (int j = i; j > 0; j--) {//第i躺的第i个数据和排好序的部分做比较
if (arr[j] < arr[j - 1]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}else {//比排好序部分最大的数还大就进行下一轮
break;
}
}
}
return arr;
}
}