Nhungftu2 / cautrucdulieu-giaithuat

0 stars 0 forks source link

Insertion sort #1

Open Nhungftu2 opened 2 years ago

Nhungftu2 commented 2 years ago

public class InsertedSoft { public static void main(String[] args) { int[] arr= {1,3,15,2,9,4,0,90,6,2}; insertedSoft(arr); showArr(arr);

}

public static int[] insertedSoft(int[] arr){
    int length = arr.length;

    for (int i=1; i < length ; i++){
        int index = arr[i];
        int j= i-1;
        for(; j>=0; j--){
            if(arr[j]> index){
                arr[j+1]=arr[j];
            }else{
                break;
            }
            arr[j]= index;
        }

    }
    return arr;
}
public static void showArr(int[] arr){
    int length = arr.length;
        for (int i=0; i< length; i++){
            System.out.print(arr[i]+ " ");
        }
}

}

Nhungftu2 commented 2 years ago
public void insertSort(int [] a){
    // luu du lieu mang a sang mang b
    int length = a.length;
    int[] b = new int[length];
    for(int i=0; i<length ; i++){
        b[i] = a[i];
    }
    //display(b);
    // Thực hiện thuật toán Insertion Sort trên mảng b
    for (int i=1; i < length ; i++){
        int index = b[i];
        int j= i-1;
        for(; j>=0; j--){
            if(b[j]> index){
                b[j+1]=b[j];
            }
            else{
                break;
            }
            //b[j]= index;
        }
        b[j+1]= index;
    }
    //hiển thị kết quả sắp xếp
    display(b);
}