首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将插入排序伪代码转换为运行Java代码

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

Stack Overflow用户
提问于 2013-06-11 11:50:05
回答 2查看 5.4K关注 0票数 1

我试图将这个插入排序伪代码转换成java,但是没有得到正确的输出。下面是伪代码

代码语言:javascript
复制
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代码

代码语言:javascript
复制
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}。

EN

回答 2

Stack Overflow用户

发布于 2013-06-11 11:58:04

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2014-04-11 01:10:29

代码语言:javascript
复制
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);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17036216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档