转换插入将伪代码转换为运行Java代码

时间:2013-06-11 03:50:05

标签: arrays algorithm sorting pseudocode insertion-sort

我尝试将此插入排序伪代码转换为java但未获得正确的输出。这是伪代码

INSERTION-SORT(A)
1 for j ← 2 to length[A]
2   do key ← A[j]
3     ▹ Insert A[j] into the sorted sequence A[1  j - 1].
4     i ← j - 1
5     while i > 0 and A[i] > key
6      do A[i + 1] ← A[i]
7         i ← i - 1
8     A[i + 1] ← key

这是我的Java代码

public class Insertion {

    public static void print(int[] A){          
        for(int i = 0; i > A.length; i++){              
            System.out.print(A[i] + " ");               
            }           
        System.out.println(); 
    }

    public static void insertionSort(int[] A){          
        for(int j = 1; j < A.length; j++){

            int key = A[j];
            int i = j - 1;

            while(i >= 0 && A[i] > key){
                A[i + 1] = A[i];
                i = i - 1;
            }               
            key = A[i + 1];             
        }           
        print(A);
    }

    public static void main(String[] args){         
        int[] x = {5,2,4,6,1,3};
          insertionSort(x);
    }
}

打印出来的是同一个数组A.没有排序或只是{5,2,4,6,1,3}。

2 个答案:

答案 0 :(得分:1)

public class InsertionSort {

    private static long[] arr;

    /**
     * Run Insertion Sort algorithm
     *
     * @param array data structure used to run the algorithm
     */
    public static void run(long[] array) {
        arr = array;
        int j;

        for (int i = 1; i < arr.length; i++) {
            long temp = arr[i];
            j = i;
            while (j > 0 && temp <= arr[j - 1]) {
                arr[j] = arr[j - 1];
                j--;
            }
            arr[j] = temp;
        }
    }
}

答案 1 :(得分:0)

public class Insertion {

    public static void print(int[] A){

        for(int i = 0; i > A.length; i++){

            System.out.print(A[i] + " ");

            }

        System.out.println(); 
    }

    public static void insertionSort(int[] A){

        for(int j = 1; j < A.length; j++){

            int key = A[j];
            int i = j - 1;

            while(i >= 0 && A[i] > key){
                A[i + 1] = A[i];
                i = i - 1;
            }

            key = A[i + 1];

        }

        print(A);
    }

    public static void main(String[] args){

        int[] x = {5,2,4,6,1,3};
        insertionSort(x);
    }
}