Is my code a correct implementation of insertion sort?

隐身守侯 提交于 2019-12-12 01:24:42

问题


This code sorts correctly. Is this an insertion sort?

import java.util.Scanner;
public class InsertionSort {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of elements: ");
        int count;
        count = sc.nextInt();
        int[] a = new int[count];
        System.out.println("Enter elements: ");
        for(int i = 0 ; i<count;i++){
            a[i] = sc.nextInt();
        }
        int j,temp;
        System.out.println("aftr insertion sort :");
        for(int i = 1 ; i<count;i++){
            j=i;
            while(j>0 && a[j-1] > a[j] ){
                temp = a[j];
                a[j] = a[j-1];
                a[j-1] = temp;
                j--;
            }
        }
        for(int i = 0 ; i<count;i++){
            System.out.print(a[i]+"  ");
        }
    }
}

回答1:


I've focused on the second of the three for loops, the one where the actual sorting happens. That loop looks fine to me.



来源:https://stackoverflow.com/questions/12333715/is-my-code-a-correct-implementation-of-insertion-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!