【问题标题】:Converting Insertion Sort pseudocode to running Java code将插入排序伪代码转换为运行 Java 代码
【发布时间】:2013-06-11 03:50:04
【问题描述】:

我尝试将此插入排序伪代码转换为 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}。

【问题讨论】:

  • 了解基本思想后,自己编写应该很简单,将有序数组中的每个项目插入到有序数组中,每次插入时,通过推送当前项目保持其有序,直到它不再违反订单条件

标签: arrays algorithm sorting pseudocode insertion-sort


【解决方案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;
        }
    }
}

【讨论】:

    【解决方案2】:
    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);
        }
    }
    

    【讨论】:

    • 你应该详细说明你的答案
    猜你喜欢
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多