我如何做到所以我的最高号码只是移动到第一个位置。这就是我到目前为止所拥有的
public static void main(String[] args) {
//array of 10 numbers
int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
//assign first element of an array to largest and smallest
int smallest = numbers[0];
int largetst = numbers[0];
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > largetst)
largetst = numbers[i];}
System.out.println("Numbers : " + numbers);
}
}
答案 0 :(得分:1)
public static void main(String[] args) {
//array of 10 numbers
int numbers[] = new int[] { 32, 43, 53, 54, 32, 65, 63, 98, 43, 23 };
//assign first element of an array to largest and smallest
int tmp = 0;
int largetst = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largetst){
largetst = numbers[i];
}
}
for(int i = 1; i < numbers.length; i++){
if(largetst == numbers[i]){
tmp = numbers[0];
numbers[0] = largetst;
numbers[i] = tmp;
}
}
System.out.println("Numbers : " + numbers[0]);
}
虽然它不是最佳的,但请使用此方法并进一步优化它,谢谢
答案 1 :(得分:0)
请参阅Demo
如果我理解你的问题,那么这可能就是答案:
**
您只需要阵列前端的最高编号。 没有更多信息
**
public static void main(String[] args) {
//array of 10 numbers
int numbers[] = new int[]{32, 43, 53, 54, 32, 65, 663, 98, 43, 23};
//assign first element of an array to largest and smallest
int smallest = numbers[0];
int largest = numbers[0];
//to keep track of the largest number's index
int indexOfLargestNumber = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
indexOfLargestNumber = i;
largest = numbers[i];
}
}
// swap the position of the front number and the highest number
int temp = numbers[0];
numbers[0] = largest;
numbers[indexOfLargestNumber] = temp;
//printing the whole array
for(int i = 0;i<numbers.length;i++){
System.out.print(numbers[i]+" ");
}
}
答案 2 :(得分:0)
你可以做什么来获得最开始的数字:每当你找到一个更大的数字时,用第一个交换它们。
public static void main(String[] args) {
//array of 10 numbers
int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
// temporary variable for swapping numbers
int tmp;
for(int i=1; i < numbers.length; i++)
{
// check if i-th number bigger than first one
if(numbers[i] > numbers[0]) {
// if yes - swap!
tmp = numbers[0];
numbers[0] = numbers[i];
numbers[i] = tmp;
}
}
System.out.println("Largest number : " + numbers[0]);
}
或者 - 而不是交换它们 - 你可以只存储最大数字的位置,然后在循环后交换它们。 (节省一些内存和性能)