#将一个记录插入到已经拍好序的有序表中,使得有序表加一。
class insert{
public void insert(int[] arr) {
int i,j,temp;
for(i=1;i<arr.length;i++) {
if(arr[i]<arr[i-1]) { //将arr[i]插入有序表中
temp=arr[i];//暂存于temp中
for(j=i-1;arr[j]>temp;j--) {
arr[j+1]=arr[j];//将大于temp的元素后移
if(j==0) break;
}
if(j==0)
arr[j]=temp;
else
arr[j+1]=temp;
}
}
}
}
public class InsertSort {
public static void main(String[] args) {
int[] arr={55,44,85,16,12,17,99,65};
insert InsertSort=new insert();
InsertSort.insert(arr);
System.out.println("直接插入排序后的顺序:");
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]+" ");
}
}
}
Python直接插入排序
def InsertSort(items):
length=len(items)
for i in range(1,length):
value=items[i]
insert_index=-1
for j in range(i-1,-1,-1):
if value<items[j]:
items[j+1]=items[j]#将元素往下一个位置移动
insert_index=j#记录好下标
if insert_index!=-1:
items[insert_index]=value#将元素插入到对应的位置
print(items)
if __name__=="__main__":
items=[44,55,6,98,56,88,74]
InsertSort(items)