java如何打印出数组中的最后一项
我正在尝试创建一个程序,它将运行输入的整数列表,从最小到最大排序,然后打印出最后一项(最大)、中间输入的项和第一项(最小整数)
正如你从代码中看到的,我有这些项目的平均值
“bubbleSort”方法将它们按顺序排列并打印出排序后的数组
有什么建议吗
代码:
class statistics{
public static void main(String agrs[]){
System.out.println("Enter the number of integers you want to input?");
int n = EasyIn.getInt();
//declare arrey called numbers and give it the length of the number enter.
int[] numbers = new int[n];
for(int i=0; i<numbers.length; i++){
System.out.println("Enter number: " + (i+1));
numbers[i] = EasyIn.getInt();
}// end of for loop
// add a switch case for the print outs and a menu.
bubbleSort(numbers);
System.out.println("The average is " + averageMethod(numbers));
}// end of main method.
public static int averageMethod(int[] nums){
int total=0;
int average=0;
for(int i=0; i<nums.length; i++){
total = total+nums[i];
average = total/nums.length;
}// end of for loop
return average;
}// end of totalMethod
public static void bubbleSort(int[] ar) {
int temp;
// this code does the bubble sort
System.out.println();
for(int i = ar.length -1; i>0; i--){
for(int j=0;j<i; j++){
if(ar[j]>ar[j+1]){
temp=ar[j];
ar[j]=ar[j + 1];
ar[j+1]= temp;
}
}
System.out.print("The sorted array is : ");
for(int b=0; b<ar.length; b++){
System.out.print(ar[n] + ", ");
}
System.out.println();
}
} // end of buble sort
}// end of class.
# 1 楼答案
除了Smutje所说的,为了得到中间的项目: 如果n是奇数,那么它将是
arr[(n/2)+1]
,但是如果n是偶数,那么它取决于你认为的“中间”,举个例子: 如果n=4,那么n/2=2,这是第三个指数,(n-1)/2=1,这是第二个指数,现在哪一个是中间的# 2 楼答案
要打印第一个、中间和最后一个,可以执行以下操作:
另一个建议是不要使用冒泡排序:)
# 3 楼答案
如果有一个长度为
n
的升序排序数组arr
,则最小的元素位于arr[0]
,最大的元素位于arr[n - 1]