我是java编程的新手,并尝试编写一个对Arrays进行排序的函数。我知道我的代码对于这么简单的任务来说非常强大,但它是我考虑排序的第一种方式,所以我就去了。我的逻辑是采用一个数组,用所有0做一个相同长度的数组。然后使用for循环查找未排序数组的最小值,将其放在新数组的开头,然后用未排序数组的最大值替换未排序数组的min,直到整个数组全部为maxes并且I&# 39; ve填充要排序的数组。我将在下面举几个例子,因为它有点难以解释:
-Starting Array:[2, 3, 1, 4]
-1st Execution: [2, 3, 1, 4] [0, 0, 0, 0]
-2nd: [2, 3, 4, 4] [1, 0, 0, 0]
-3rd: [4, 3, 4, 4] [1, 2, 0, 0]
-4th: [4, 4, 4, 4] [1, 2, 3, 0]
-5th: [4, 4, 4, 4] [1, 2, 3, 4]
我编写的代码返回数组的min,找到min的索引,并返回数组的最大值。我的方法是继续这个过程,并保持一个计数器,即for循环找到min的时间,然后当它等于数组长度-1时停止。我在上一个方法中遇到了问题 - sortMe - 因为我的回复没有编译,错误是:
Error: incompatible types
found : int[]
required: java.util.Arrays
我附上了以下所有代码:
import java.util.Arrays;
public class Homework4 {
public static void main (String[] args) {
int[] a = {20,2,5};
System.out.println(Homework4.minArray(a));
System.out.println(Homework4.maxArray(a));
System.out.println(Homework4.minIndex(a));
System.out.println( Arrays.toString(a));
}
/* 1 This method will mimic the sort methond for Arrays
* It will be called sortMe and will take in an array and produce a sorted array
* In order to do this I will also create two methods: min and max
* The numbers in the array will be of type Int
* Homework4.sortMe([0 , 3, 4, 2, 1, 7]) -> [0 , 1, 2, 3, 4, 7]
* Homework4.sortMe([0]) -> [0]
* Homework4.sortMe([3, 8, 2, 14, 1)] -> [1, 2, 3, 8, 14]
* Template:*/
public static int minArray (int[] x) { //Produces the Minimum of an Array
int minVal = x[0];
for (int i = 0; i < (x.length - 1); i = i + 1) {
if( x[i] < minVal) {
minVal = x[i];}
}
return minVal;}
public static int minIndex (int[] x) { //Returns the index of the Minimum
int minVal = x[0];
int index = 0;
for (int i = 0; i < (x.length - 1); i = i + 1) {
if( x[i] < minVal) {
minVal = x[i];
index = i;}
}
return index;}
public static int maxArray (int[] x) { //Produces the Maximum of an Array
int maxVal = x[0];
for (int i = 0; i < (x.length - 1); i = i + 1) {
if( x[i] > maxVal) {
maxVal = x[i];}
}
return maxVal;}
public static Arrays sortMe (int[] x) { //Sorts an Array
int[] sortedArray = new int [x.length];
int minIterations = 0;
while (minIterations < x.length-1) {
for(int i = 0; i < x.length-1; i = i +1){
sortedArray[i] = Homework4.minArray(x);
x[Homework4.minIndex(x)] = Homework4.maxArray(x);
minIterations++;
}}
return sortedArray; }
}
谢谢!
答案 0 :(得分:5)
我想你要返回一个整数数组吗?我假设你已经将sortedArray声明为一个整数数组。
在这种情况下,方法头需要返回类型为整数数组,与使用整数数组作为参数相同:
所以:
public static Arrays sortMe (int[] x)
变为:
public static int[] sortMe (int[] x)
答案 1 :(得分:1)
public static Arrays sortMe (int[] x) {...}
应该是:
public static int[] sortMe (int[] x) {...}
答案 2 :(得分:-1)
将返回类型更改为int []而不是Araays。
@Configuration