gpt4 book ai didi

java - 找到数组中最小和最大的元素并打印元素的位置

转载 作者:行者123 更新时间:2023-12-02 07:25:29 25 4
gpt4 key购买 nike

在不使用算法的情况下查找数组中最大和最小元素并打印其索引位置的最简单方法是什么。有没有办法使用循环或 if 语句来做到这一点,因为我是 java 新手,据我目前所知。

这是我的数组代码:

import java.io.*;
public class Tut2ArraysQ4
{

public static void main(String [] args) throws IOException
{
BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));

int []item=new int[5];
for (int i = 0; i < item.length; i++)
{
System.out.println("Enter a number: ");
int num=Integer.parseInt(kbd.readLine());
System.out.println("Index " + i + " Contains Number " + num);
}

}//end class
}//end main

非常感谢您的帮助

最佳答案

您声明两个变量等于数组第一个位置的元素,另外两个变量等于第一个位置。

int min = array[0];
int max = array[0];
int posMin = 0;
int posMax = 0;

对数组的所有位置进行 for 迭代:

   for(all the position of the array)
// if current position bigger than max
// max = element of the array in the current position
// posMin = current position
// if current position smaller than min
// min = element of the array in the current position
// posMax = current position

另一种方法是对数组进行排序,最小的元素将位于数组的第一个位置,最大的元素将位于数组的最后一个位置。但是,此解决方案通常需要 N lg N,而我在第一个解决方案中发布的性能为 N。如果您使用基数排序,则需要 k N,但是:

Sometimes k is presented as a constant, which would make radix sort better (for sufficiently large n) than the best comparison-based sorting algorithms, which are all O(n·log(n)). However, in general k cannot be considered a constant.

了解更多 about

关于java - 找到数组中最小和最大的元素并打印元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13631343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com