插入排序伪代码和实现

插入算法伪代码

for j=2 to A.length
    key=A[j]
    i=j-1;
    while i>0 and A[i]>key
        A[i+1]=A[i]
        i=i-1
    A[i+1]=key

c实现

void main(){
    int A[]={3,8,1,4,5,0,2,5};
    int j;
    int i=0;
    int key;
    int len=sizeof(A)/sizeof(A[0]);
    for(j=1;j<len;j++){
        key=A[j];
        i=j-1;
        while(i>=0 && A[i]>key){
            A[i+1]=A[i];
            i=i-1;
        }
        A[i+1]=key;
    }
    for(j=0;j<len;j++){
        printf("%d ",A[j]);
    }
}

java代码实现

public class Main {

    public static void main(String[] args) {
        int [] arr={3,8,1,4,5,0,2,5};
            for(int j=1;j<arr.length;j++){
                int key=arr[j];
                int i=j-1;
                while(i>=0 && arr[i]>key){
                     arr[i+1]=arr[i];
                     i--;
                }
                arr[i+1]=key;
            }
            for(int j=0;j<arr.length;j++){
                 System.out.print(arr[j]+" ");
            }
    }
}

没有更多推荐了,返回首页