《插入排序》——Java实现
插入排序其实就是为元素确定它的位置。从数组第二个元素开始,它的左边的元素都是有序的,然后为当前元素确定它在左边序列中的位置,也就是找到一个比当前元素小的元素,那么它的右边的位置就是当前元素的位置;每次比较都会多一个元素,比较次数也就多一次,平均时间复杂度是O(n^2)。
1 public class InsertSort implements IArraySort{ 2 3 @Override 4 public int[] sort(int[] arr) { 5 // 复制数组,不对入参修改 6 int[] newArr = Arrays.copyOf(arr, arr.length); 7 8 for (int i = 1; i < newArr.length; i++) { 9 int temp = newArr[i]; 10 11 int j = i; 12 while (j > 0 && newArr[j - 1] > temp){ 13 newArr[j] = newArr[j - 1]; 14 j--; 15 } 16 17 if (i != j){ 18 newArr[j] = temp; 19 } 20 } 21 22 return newArr; 23 } 24 }
public class InsertSort implements IArraySort{
@Override
public int[] sort(int[] arr) {
// 复制数组,不对入参修改
int[] newArr = Arrays.copyOf(arr, arr.length);
for (int i = 1; i < newArr.length; i++) {
int temp = newArr[i];
int j = i;
while (j > 0 && newArr[j - 1] > temp){
newArr[j] = newArr[j - 1];
j--;
}
if (i != j){
newArr[j] = temp;
}
}
return newArr;
}
}

浙公网安备 33010602011771号