我非常开始编程和Java。我在学习中从互联网上获取了以下代码。
import java.util.*;
class Example{
public static void sort(int[] x){
int max=x[0];
int index=0;
for(int j=1; j<x.length; j++){
if(x[j]>max){
max=x[j];
index=j;
}
}
x[index]=x[x.length-1];
x[x.length-1]=max;
}
public static void main(String args[]){
int[] xr={89,87,67,91,19,27,37,97,83,63,72,71};
System.out.println(Arrays.toString(xr));
sort(xr);
System.out.println(Arrays.toString(xr));
}
}
工作正常。但我无法理解以下代码段,
int max=x[0];
int index=0;
for(int j=1; j<x.length; j++){
if(x[j]>max){
max=x[j];
index=j;
}
}
请您描述一下,我只是逐行介绍
int max=x[0]; //save the first element of the array into max
int index=0; //initialize the index variable
//loop over the array i.e. x starting with second element i.e x[1]
for(int j=1; j<x.length; j++){
//if current element in array is bigger than the max (x[0] in first run)
if(x[j]>max){
max=x[j]; //then set the max to be the current element
index=j; //update the index of the current max (is 0 in first run)
}
}
我建议您定义一些具有不同大小和数据的数组,然后手动跟踪步骤。最初写下每个变量的值,然后逐步更新。那就更好了。