首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >插入排序-降序

插入排序-降序
EN

Stack Overflow用户
提问于 2013-03-08 23:53:56
回答 4查看 25.4K关注 0票数 2

抱歉,如果这是一个基本的问题…

我只是想学习更多关于算法的知识。

我写了一个简单的代码来按升序执行插入排序,但是由于某些原因,我不能按降序执行排序。

我尝试将比较键(while (i >0 && ai >键)改为(i >0 && ai <键))..它似乎部分工作,但第一个元素没有得到排序,我得到了下面的results..Can有人让我知道我哪里错了?

1 11 10 9 5 4 3 2

代码语言:javascript
复制
public class InsertionSort {
    public static void main(String args[]) {
        int[] a = { 1,10,11,5, 9, 3, 2, 4 };
        // Loop through the entire array length. Consider you already have one
        // element in array, start comparing with
        // first element
        for (int j = 1; j < a.length; j++) {
            // Get the key (The value that needs to be compared with existing
            // values.
            int key = a[j];
            // Get the array index for comparison, we need to compare with all
            // other elements in the array with
            // key
            int i = j - 1;
            // While i > 0 and when key is less than the value in the array
            // shift the value and insert
            // the value appropriately.
            //System.out.println(j);
            while (i > 0 && a[i] < key) {
                a[i + 1] = a[i];
                i = i - 1;
                a[i + 1] = key;
            }
        }
        for (int k = 0; k < a.length; k++) {
            System.out.println(a[k]);
        }
    }
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-03-08 23:56:53

你永远不会接触到a[0]

代码语言:javascript
复制
while (i > 0 && a[i] < key) {

因此,它不会被排序到其应有的位置。使用>=而不是>

代码语言:javascript
复制
while (i >= 0 && a[i] < key) {

当按升序排序时,也会出现同样的问题。

票数 9
EN

Stack Overflow用户

发布于 2013-03-08 23:56:59

数组中的第一个元素是a[0]。你不能在任何地方比较它。

票数 2
EN

Stack Overflow用户

发布于 2013-03-08 23:59:25

从0开始,数组a[]到达第一个元素a,因此aj中的第一个元素将是a,而不是a1;

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15297997

复制
相关文章

相似问题

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