查詢列表中最大和最小元素位置的 Java 程式
查詢列表中最大和最小元素位置的 Java 程式如下 −
示例
import java.util.*;
import java.util.Arrays;
import java.util.Collections;
public class Demo{
public static int index_val(int my_arr[], int t){
if (my_arr == null){
return -1;
}
int len = my_arr.length;
int i = 0;
while (i < len){
if (my_arr[i] == t){
return i;
} else {
i = i + 1;
}
}
return -1;
}
public static void main(String[] args){
Integer[] my_arr = { 34, 67, 89, 99, 45, 77 };
int[] my_int_arr = { 34, 67, 89, 99, 45, 77 };
int min_val = Collections.min(Arrays.asList(my_arr));
int max_val = Collections.max(Arrays.asList(my_arr));
System.out.println("The minimum value in the array is : " + min_val);
System.out.println("The maximum value in the array is : " + max_val);
System.out.println("The position of the minimum value is: " + index_val(my_int_arr, min_val));
System.out.println("The position of the maximum value is: " + index_val(my_int_arr, max_val));
}
}輸出
The minimum value in the array is : 34 The maximum value in the array is : 99 The position of the minimum value is: 0 The position of the maximum value is: 3
Demo 類中定義了一個線性查詢函式,用於查詢引數中指定元素的索引。main 函式定義了一個數組,並從陣列中找出最小值和最大值。在此陣列上呼叫線性查詢函式,並將最小值和最大值也作為引數傳遞給線性查詢函式。這將給出陣列的最小值和最大值的索引。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP