Yêu cầu
– Nhập vào mảng 1 chiều số nguyên
– Viết hàm tìm vị trí phần tử dương nhỏ nhất trong mảng số nguyên. Nếu mảng không có số dương, trả về -1
Giải thuật
– Dùng vòng lặp for() và câu lệnh if() để kiểm tra.
Code
package net.vncoding; public class JavaCore { static int arr[] = {-1, -3, -9, 7, 8, 16, 23, 2, 100}; public static void main(String[] args) { int pos = find_pos_min_positive(arr); System.out.println("Position of minimum positive value in array is " + (pos + 1)); } public static int find_pos_min_positive(int arr[]) { int min = 0; int pos = -1; int i; for(i = 0; i < arr.length; i++) { if((min == 0 || min > arr[i]) && arr[i] > 0 ) { min = arr[i]; pos = i; } } return pos; } }
Kết quả
Leave a Reply
You must be logged in to post a comment.