按升序对数组的元素进行排序 [英] Sort elements of an array in ascending order

查看:120
本文介绍了按升序对数组的元素进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按升序对数组进行排序。由于某种原因,它只执行一次for循环。为什么它不会继续进行,直到所有内容都被排序?

I'm trying to sort an array in ascending order. For some reason it only performs the for loop once. Why doesn't it keep going until everything is sorted?

这是一个赋值所以我不允许使用现有的排序方法。我应该自己编写这个方法。

It's for an assignment so I am not allowed to use existing sort methods. I'm supposed to write the method myself.

public class Sudoku {
    public static void main(String[] args) {
        int[] a = { 1, 4, 3, 5, 2 };
        System.out.println(Arrays.toString(sortArray(a)));
    }

    public static int[] sortArray(int[] nonSortedArray) {
        int[] sortedArray = new int[nonSortedArray.length];
        int temp;

        for (int i = 0; i < nonSortedArray.length - 1; i++) {
            if (nonSortedArray[i] > nonSortedArray[i + 1]) {
                temp = nonSortedArray[i];
                nonSortedArray[i] = nonSortedArray[i + 1];
                nonSortedArray[i + 1] = temp;
                sortedArray = nonSortedArray;
            }
        }

        return sortedArray;
    }
}


推荐答案

public static int[] sortArray(int[] nonSortedArray) {
        int[] sortedArray = new int[nonSortedArray.length];
        int temp;
        for (int j = 0; j < nonSortedArray.length - 1; j++) {// added this for loop, think about logic why do we have to add this to make it work

        for (int i = 0; i < nonSortedArray.length - 1; i++) {
            if (nonSortedArray[i] > nonSortedArray[i + 1]) {
                temp = nonSortedArray[i];
                nonSortedArray[i] = nonSortedArray[i + 1];
                nonSortedArray[i + 1] = temp;
                sortedArray = nonSortedArray;

            }
        }
        }
        return sortedArray;
    }

输出: [1,2,3, 4,5]

output:[1, 2, 3, 4, 5]

//making use of j

public static int[] sortArray(int[] nonSortedArray){
    int[] sortedArray = new int[nonSortedArray.length];
    int temp;
    for (int i = 0; i <= nonSortedArray.length; i++) 
    {
        for (int j = i+1; j < nonSortedArray.length; j++)
        {
            if (nonSortedArray[i] > nonSortedArray[j]) 
            {
                temp = nonSortedArray[i];
                nonSortedArray[i] = nonSortedArray[j];
                nonSortedArray[j] = temp;
                sortedArray = nonSortedArray;
            }
        }
    }
    return sortedArray;
}

这篇关于按升序对数组的元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆