如何编写一种从低到高对数组中的数字进行排序的方法

问题描述 投票:-1回答:1

此代码中有错误:

ArraySortSearch.java:12:错误:不兼容的类型:int不能为转换为int []int [] mySorted = sort(myNumbers);^ ArraySortSearch.java:56:错误:不兼容的类型:int []无法转换为int返回一个;

我不久前才开始学习Java。这是如此困难:(我该如何解决?

//not allowed to use import java.util
public class ArraySortSearch { // shouldn't be changed from here

public static void main(String[] args) {


    int [] myNumbers = {15,12,23,0,10,55,2,78,9,6,1,4,11};

    System.out.println("Looking for numer 55: ");
    System.out.println(find(myNumbers,55));

    System.out.println("Sorted Array:");
    int [] mySorted = sort(myNumbers);

    for(int i = 0; i< mySorted.length; i++) {
        System.out.println(mySorted[i]);

        }

} //to here

    public static int find(int [] a, int number){ //this method works

        for(int i=0; i<a.length; i++){

            if(a[i]==number){

                return i;

            }

            else{
                continue;
            }
        }

        return -1;

    }


    public static int sort(int [] a){ //this method is the problem

        for(int b=0; b<a.length; b++){

            for(int i =1; i<a.length; i++){

                if(a[b]<a[i]){
                    int temp = a[b];
                    a[b] = a[i];
                    a[i] = temp;
                }

            }

        }
        return a;
    }

}

谢谢您!

java arrays
1个回答
0
投票

您的返回类型是int,但a是数组。由于您要对数组进行排序,因此返回类型为void,无需返回任何内容。

此外,使您的外循环转到a.length-1,并使内循环从b+1开始。


-1
投票
REAL PROGRAMMERS使用了良好的格式:)我称它为“简约编程”,它每次都对我有用。

public static int find(int [] a, int number) { for(int i=0; i<a.length; i++) if(a[i]==number) return i; return -1; } public static void sort(int[] a) { for(int i=0; i < (a.length-1); i++) for(int j=(i+1); j < a.length; j++) if(a[j]<a[i]) { int temp=a[i]; a[i]=a[j]; a[j]=temp; } // Forward Sort, For Reverse-Sort Use: if(a[i]<a[j]) }

© www.soinside.com 2019 - 2024. All rights reserved.