Найти два наименьших (минимальных) элемента массива
Просмотров 7.6к. Обновлено 15 октября 2021
В одномерном массиве целых чисел определить два наименьших элемента. Они могут быть как равны между собой (оба являться минимальными), так и различаться.
Сначала можно найти минимальный элемент массива. После этого искать второй минимум, исключив их поиска первый с помощью if. Данный способ рассматривается здесь по отношению к двум наибольшим элементам.
Сложнее задачу решить, используя один цикл перебора.
Предположим, что двумя наименьшими элементами массива являются первый и второй элемент. Присвоим их индексы переменным m1 и m2. При этом, если первый элемент меньше второго, то его индекс присвоим m1, иначе m1 получит значение второго элемента, а m2 первого.
Начнем перебирать массив в цикле, начиная с третьего элемента. Если он меньше элемента, чей индекс хранится в m1, то присвоим индекс текущего элемента m1. Иначе (если значение по индексу m1 меньше, чем по индексу i) будем проверять, не меньше ли значение по индексу i, того что по индексу m2.
Есть один не очевидный нюанс. Допустим, в m1 указывало на значение 5, а m2 — на 10. Очередной элемент равен 3. Мы меняем m1, и забываем о числе 5. Однако оно может оказаться как раз вторым минимумом массива.
Поэтому в программе при изменении значения m1 надо предусмотреть проверку, не меньше ли теряемое значение, чем то, что хранится по индексу m2.
Pascal
const
N = 10;
var
a: array[1..N] of integer;
i, min1, min2, buff: byte;
begin
randomize;
for i:=1 to N do begin
a[i] := random(100);
write(a[i]:4);
end;
writeln;if a[1] < a[2] then begin
min1 := 1;
min2 := 2;
end
else begin
min1 := 2;
min2 := 1;
end;for i:=3 to N do
if a[i] < a[min1] then begin
buff := min1;
min1 := i;
if a[buff] < a[min2] then
min2 := buff;
end
else
if a[i] < a[min2] then
min2 := i;writeln('№', min1:2,': ', a[min1]:2);
writeln('№', min2:2,': ', a[min2]:2);
end.
8 66 40 40 0 14 50 74 93 71
№ 5: 0
№ 1: 8
Язык Си
#include < stdio.h>
#define N 10
main() {
int a[N];
int i, min1, min2, buff;
srand(time(NULL));
for (i=0; i< N; i++) {
a[i] = rand() % 100;
printf("%3d", a[i]);
}
printf("n");if (a[0] < a[1]) {
min1 = 0;
min2 = 1;
} else {
min1 = 1;
min2 = 0;
}for (i=2; i< N; i++) {
if (a[i] < a[min1]) {
buff = min1;
min1 = i;
if (a[buff] < a[min2]) min2 = buff;
} else {
if (a[i] < a[min2]) min2 = i;
}
}printf("№%2d:%3dn",min1+1,a[min1]);
printf("№%2d:%3dn",min2+1,a[min2]);
}
97 20 88 29 20 43 87 19 33 26
№ 8: 19
№ 5: 20
Python
найти два минимальных элемента массива python
from random import random
N = 10
a = []
for i in range(N):
a.append(int(random()*100))
print("%3d" % a[i], end='')
print()if a[0] > a[1]:
min1 = 0
min2 = 1
else:
min1 = 1
min2 = 0for i in range(2,N):
if a[i] < a[min1]:
b = min1
min1 = i
if a[b] < a[min2]:
min2 = b
elif a[i] < a[min2]:
min2 = iprint("№%3d:%3d" % (min1+1, a[min1]))
print("№%3d:%3d" % (min2+1, a[min2]))# Вариант 2
from random import randint
array = [randint(1, 20) for i in range(10)]
print(array)min1 = min(array)
array.remove(min1)
min2 = min(array)print(min1)
print(min2)
14 3 40 56 42 43 89 69 64 72
№ 1: 14
№ 2: 3
КуМир
алг два минимальных
нач
цел N = 10
цел таб arr[1:N]
цел i,m1,m2,b
нц для i от 1 до N
arr[i] := irand(10,100)
вывод arr[i]:3
кц
вывод нсесли arr[1] < arr[2] то
m1 := 1
m2 := 2
иначе
m1 := 2
m2 := 1
всенц для i от 3 до N
если arr[i] < arr[m1] то
b := m1
m1 := i
если arr[b] < arr[m2] то
m2 := b
все
иначе
если arr[i] < arr[m2] то
m2 := i
все
все
кц
вывод "№",m1:2,":",arr[m1]:3,нс
вывод "№",m2:2,":",arr[m2]:3,нс
кон
65 32 24 86 65 58 67 55 33 96
№ 3: 24
№ 2: 32
Basic-256
N = 10
dim arr(N)
for i=0 to N-1
arr[i] = int(rand*100)
print arr[i] + " ";
next iif arr[0] < arr[1] then
m1 = 0
m2 = 1
else
m1 = 1
m2 = 0
endiffor i=2 to N-1
if arr[i] < arr[m1] then
b = m1
m1 = i
if arr[b] < arr[m2] then
m2 = b
endif
else
if arr[i] < arr[m2] then
m2 = i
endif
endif
next iprint (m1+1) + ": " + arr[m1]
print (m2+1) + ": " + arr[m2]
81 7 25 71 23 9 56 91 73 64
2: 7
6: 9
Write an efficient C++/C program to find the smallest and second smallest element in an array.
Example:
Input: arr[] = {12, 13, 1, 10, 34, 1}
Output: The smallest element is 1 and
second Smallest element is 10
Approach 1:
A Simple Solution is to sort the array in increasing order. The first two elements in the sorted array would be the two smallest elements. In this approach, if the smallest element is present more than one time then we will have to use a loop for printing the unique smallest and second smallest elements.
Below is the implementation of the above approach:
C#
using System;
public class GFG {
static public void Main()
{
int[] arr = { 111, 13, 25, 9, 34, 1 };
int n = arr.Length;
Array.Sort(arr);
Console.WriteLine("smallest element is " + arr[0]);
Console.WriteLine("second smallest element is "
+ arr[1]);
}
}
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 111, 13, 25, 9, 34, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n);
cout << "smallest element is " << arr[0] << endl;
cout << "second smallest element is " << arr[1];
return 0;
}
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[])
{
int arr[] = { 111, 13, 25, 9, 34, 1 };
int n = arr.length;
Arrays.sort(arr);
System.out.println("smallest element is " + arr[0]);
System.out.println("second smallest element is "
+ arr[1]);
}
}
Python3
arr = [111, 13, 25, 9, 34, 1]
n = len(arr)
arr.sort()
print("smallest element is "+str(arr[0]))
print("second smallest element is "+str(arr[1]))
Javascript
<script>
let arr = [111, 13, 25, 9, 34, 1];
let n = arr.length;
arr.sort();
document.write("smallest element is "+arr[0],"</br>");
document.write("second smallest element is "+arr[1],"</br>");
</script>
Output
smallest element is 1 second smallest element is 9
Time complexity: O(N*logN)
Auxiliary space: O(1)
Approach 2A:
A Better Solution is to scan the array twice. In the first traversal find the minimum element. Let this element be x. In the second traversal, find the smallest element greater than x.
Using this method, we can overcome the problem of Method 1 which occurs when the smallest element is present in an array more than one time.
The above solution requires two traversals of the input array.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = {12, 13, 1, 10, 34, 1};
int n = sizeof(arr) / sizeof(arr[0]);
int smallest = INT_MAX;
for (int i = 0; i < n; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
cout << "smallest element is: " << smallest << endl;
int second_smallest = INT_MAX;
for (int i = 0; i < n; i++)
{
if (arr[i] < second_smallest && arr[i] > smallest)
{
second_smallest = arr[i];
}
}
cout << "second smallest element is: " << second_smallest << endl;
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String args[])
{
int arr[] = { 12, 13, 1, 10, 34, 1 };
int n = arr.length;
int smallest = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (arr[i] < smallest) {
smallest = arr[i];
}
}
System.out.println("smallest element is: "
+ smallest);
int second_smallest = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (arr[i] < second_smallest
&& arr[i] > smallest) {
second_smallest = arr[i];
}
}
System.out.println("second smallest element is: "
+ second_smallest);
}
}
Python
import sys
arr = [12, 13, 1, 10, 34, 1]
n = len(arr)
smallest = sys.maxint
for i in range(n):
if(arr[i] < smallest):
smallest = arr[i]
print('smallest element is: ' + str(smallest))
second_smallest = sys.maxint
for i in range(n):
if(arr[i] < second_smallest and arr[i] > smallest):
second_smallest = arr[i]
print('second smallest element is: ' + str(second_smallest))
C#
using System;
public class GFG
{
static public void Main ()
{
int[] arr = { 12, 13, 1, 10, 34, 1 };
int n = arr.Length;
int smallest = Int32.MaxValue;
for (int i = 0; i < n; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
Console.WriteLine("smallest element is: " + smallest);
int second_smallest = Int32.MaxValue;
for (int i = 0; i < n; i++)
{
if (arr[i] < second_smallest && arr[i] > smallest)
{
second_smallest = arr[i];
}
}
Console.WriteLine("second smallest element is: " + second_smallest);
}
}
Javascript
<script>
function solution( arr, arr_size)
{
let first = Number.MAX_VALUE,
second = Number.MAX_VALUE;
if (arr_size < 2)
{
document.write(" Invalid Input ");
return;
}
for (let i = 0; i < arr_size ; i ++)
{
if (arr[i] < first){
first = arr[i];
}
}
for (let i = 0; i < arr_size ; i ++){
if (arr[i] < second && arr[i] > first){
second = arr[i];
}
}
if (second == Number.MAX_VALUE )
document.write("There is no second smallest elementn");
else
document.write("The smallest element is " + first + " and second "+
"Smallest element is " + second +'n');
}
let arr = [ 12, 13, 1, 10, 34, 1 ];
let n = arr.length;
solution(arr, n);
</script>
Output
smallest element is: 1 second smallest element is: 10
Time complexity: O(N)
Auxiliary space: O(1)
Approach 2B:
Efficient Solution can find the minimum two elements in one traversal. Below is the complete algorithm.
Algorithm:
1. Initialize both first and second smallest as INT_MAX
first = second = INT_MAX
2. Loop through all the elements.
- If the current element is smaller than first, then update first and second.
- Else if the current element is smaller than second then update second.
Below is the implementation of the above approach:
C
#include <limits.h> /* For INT_MAX */
#include <stdio.h>
void print2Smallest(int arr[], int arr_size)
{
int i, first, second;
if (arr_size < 2) {
printf(" Invalid Input ");
return;
}
first = second = INT_MAX;
for (i = 0; i < arr_size; i++) {
if (arr[i] < first) {
second = first;
first = arr[i];
}
else if (arr[i] < second && arr[i] != first)
second = arr[i];
}
if (second == INT_MAX)
printf("There is no second smallest elementn");
else
printf("The smallest element is %d and second "
"Smallest element is %dn",
first, second);
}
int main()
{
int arr[] = { 12, 13, 1, 10, 34, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
print2Smallest(arr, n);
return 0;
}
C#
using System;
class GFG {
static void print2Smallest(int[] arr)
{
int first, second, arr_size = arr.Length;
if (arr_size < 2) {
Console.Write(" Invalid Input ");
return;
}
first = second = int.MaxValue;
for (int i = 0; i < arr_size; i++) {
if (arr[i] < first) {
second = first;
first = arr[i];
}
else if (arr[i] < second && arr[i] != first)
second = arr[i];
}
if (second == int.MaxValue)
Console.Write("There is no second"
+ "smallest element");
else
Console.Write("The smallest element is " + first
+ " and second Smallest"
+ " element is " + second);
}
public static void Main()
{
int[] arr = { 12, 13, 1, 10, 34, 1 };
print2Smallest(arr);
}
}
C++
#include <bits/stdc++.h>
using namespace std;
void print2Smallest(int arr[], int arr_size)
{
int i, first, second;
if (arr_size < 2) {
cout << " Invalid Input ";
return;
}
first = second = INT_MAX;
for (i = 0; i < arr_size; i++) {
if (arr[i] < first) {
second = first;
first = arr[i];
}
else if (arr[i] < second && arr[i] != first)
second = arr[i];
}
if (second == INT_MAX)
cout << "There is no second smallest elementn";
else
cout << "The smallest element is " << first
<< " and second "
"Smallest element is "
<< second << endl;
}
int main()
{
int arr[] = { 12, 13, 1, 10, 34, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
print2Smallest(arr, n);
return 0;
}
Java
import java.io.*;
class SecondSmallest {
static void print2Smallest(int arr[])
{
int first, second, arr_size = arr.length;
if (arr_size < 2) {
System.out.println(" Invalid Input ");
return;
}
first = second = Integer.MAX_VALUE;
for (int i = 0; i < arr_size; i++) {
if (arr[i] < first) {
second = first;
first = arr[i];
}
else if (arr[i] < second && arr[i] != first)
second = arr[i];
}
if (second == Integer.MAX_VALUE)
System.out.println("There is no second"
+ "smallest element");
else
System.out.println("The smallest element is "
+ first
+ " and second Smallest"
+ " element is " + second);
}
public static void main(String[] args)
{
int arr[] = { 12, 13, 1, 10, 34, 1 };
print2Smallest(arr);
}
}
Python3
import math
def print2Smallest(arr):
arr_size = len(arr)
if arr_size < 2:
print("Invalid Input")
return
first = second = math.inf
for i in range(0, arr_size):
if arr[i] < first:
second = first
first = arr[i]
elif (arr[i] < second and arr[i] != first):
second = arr[i]
if (second == math.inf):
print("No second smallest element")
else:
print('The smallest element is', first, 'and',
' second smallest element is', second)
arr = [12, 13, 1, 10, 34, 1]
print2Smallest(arr)
PHP
<?php
function print2Smallest($arr, $arr_size)
{
$INT_MAX = 2147483647;
if ($arr_size < 2)
{
echo(" Invalid Input ");
return;
}
$first = $second = $INT_MAX;
for ($i = 0; $i < $arr_size ; $i ++)
{
if ($arr[$i] < $first)
{
$second = $first;
$first = $arr[$i];
}
else if ($arr[$i] < $second &&
$arr[$i] != $first)
$second = $arr[$i];
}
if ($second == $INT_MAX)
echo("There is no second smallest elementn");
else
echo "The smallest element is ",$first
," and second Smallest element is "
, $second;
}
$arr = array(12, 13, 1, 10, 34, 1);
$n = count($arr);
print2Smallest($arr, $n)
?>
Javascript
<script>
function print2Smallest( arr, arr_size)
{
let i, first, second;
if (arr_size < 2)
{
document.write(" Invalid Input ");
return;
}
first=Number.MAX_VALUE ;
second=Number.MAX_VALUE ;
for (i = 0; i < arr_size ; i ++)
{
if (arr[i] < first)
{
second = first;
first = arr[i];
}
else if (arr[i] < second && arr[i] != first)
second = arr[i];
}
if (second == Number.MAX_VALUE )
document.write("There is no second smallest elementn");
else
document.write("The smallest element is " + first + " and second "+
"Smallest element is " + second +'n');
}
let arr = [ 12, 13, 1, 10, 34, 1 ];
let n = arr.length;
print2Smallest(arr, n);
</script>
Output
The smallest element is 1 and second Smallest element is 10
The same approach can be used to find the largest and second-largest elements in an array.
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach 3:
A N*log(N) approach using Priority_queue data structure. You can read about Priority Queue in more detail here.
C#
using System;
using System.Collections.Generic;
class GFG {
static void Main(string[] args)
{
int[] arr = { 2, 5, 7, 3, 9, 10, 11, 1 };
int n = arr.Length;
PriorityQueue<int> pq = new PriorityQueue<int>();
for (int i = 0; i < n; i++) {
pq.Enqueue(arr[i]);
}
int t = pq.Peek();
pq.Dequeue();
int w = pq.Peek();
Console.WriteLine("smallest element : " + t);
Console.WriteLine("second smallest element : " + w);
}
}
public class PriorityQueue<T> where T : IComparable<T> {
private List<T> data;
public PriorityQueue() { this.data = new List<T>(); }
public void Enqueue(T item)
{
data.Add(item);
int ci = data.Count - 1;
while (ci > 0) {
int pi = (ci - 1) / 2;
if (data[ci].CompareTo(data[pi]) >= 0)
break;
T tmp = data[ci];
data[ci] = data[pi];
data[pi] = tmp;
ci = pi;
}
}
public T Dequeue()
{
int li = data.Count - 1;
T frontItem = data[0];
data[0] = data[li];
data.RemoveAt(li);
--li;
int pi = 0;
while (true) {
int ci = pi * 2 + 1;
if (ci > li)
break;
int rc = ci + 1;
if (rc <= li
&& data[rc].CompareTo(data[ci]) < 0)
ci = rc;
if (data[pi].CompareTo(data[ci]) <= 0)
break;
T tmp = data[pi];
data[pi] = data[ci];
data[ci] = tmp;
pi = ci;
}
return frontItem;
}
public T Peek()
{
T frontItem = data[0];
return frontItem;
}
public int Count
{
get { return data.Count; }
}
}
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 2, 5, 7, 3, 9, 10, 11, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
priority_queue<int, vector<int>, greater<int> >
pq;
for (int i = 0; i < n; i++) {
pq.push(arr[i]);
}
int t = pq.top();
pq.pop();
int w = pq.top();
cout << "smallest element : " << t << endl;
cout << "second smallest element : " << w << endl;
return 0;
}
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
int arr[] = { 2, 5, 7, 3, 9, 10, 11, 1 };
int n = arr.length;
PriorityQueue<Integer> pq
= new PriorityQueue<Integer>();
for (int i = 0; i < n; i++) {
pq.add(arr[i]);
}
int t = pq.peek();
pq.poll();
int w = pq.peek();
System.out.println("smallest element : " + t);
System.out.println("second smallest element : "
+ w);
}
}
Python3
from queue import PriorityQueue
arr = [2, 5, 7, 3, 9, 10, 11, 1]
n = len(arr)
pq = PriorityQueue()
for i in range(0, n):
pq.put(arr[i])
t = pq.get()
w = pq.get()
print("smallest element :", t)
print("second smallest element :", w)
Javascript
class PriorityQueue {
constructor() {
this.values = [];
}
enqueue(val, priority) {
this.values.push({ val, priority });
this.sort();
}
dequeue() {
return this.values.shift();
}
sort() {
this.values.sort((a, b) => a.priority - b.priority);
}
get top() {
return this.values[0].val;
}
get secondTop() {
return this.values[1].val;
}
}
const arr = [2, 5, 7, 3, 9, 10, 11, 1];
const pq = new PriorityQueue();
for (let i = 0; i < arr.length; i++) {
pq.enqueue(arr[i], arr[i]);
}
const t = pq.top;
pq.dequeue();
const w = pq.top;
console.log("smallest element: ", t);
console.log("second smallest element: ", w);
Output
smallest element : 1 second smallest element : 2
Time Complexity: O(n*log(n))
In a priority queue time for adding each element is O(logn) and we are adding all the elements so the total time taken by the priority queue will be O(n*logn)
Auxiliary Space: O(n)
The extra space is used to store the elements in the priority queue.
Related Article: Minimum and Second minimum elements using minimum comparisons
Approach 4: Using list properties
Algorithm:
- Step 1: Declare a new list
- Step 2: Check length of the original list is more than 2 or not.
- Step 3: Append the smallest element from the original list into new list.
- Step 4: Count the number times smallest element appeared in the original list, then run a loop to remove all the smallest elements from the original list.
- Step 5: After removing all smallest elements, now find for 2nd smallest element using min function.
- Step 6: return new list which contains the smallest element and 2nd smallest element.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> print2Smallest(vector<int> arr)
{
vector<int> lst;
if (unordered_set<int>(arr.begin(), arr.end()).size()
== 1) {
return { -1, -1 };
}
lst.push_back(*min_element(
arr.begin(), arr.end()));
int p = *min_element(arr.begin(),
arr.end());
int c = count(arr.begin(), arr.end(),
p);
arr.erase(
remove(arr.begin(), arr.end(), p),
arr.end());
lst.push_back(*min_element(
arr.begin(),
arr.end()));
return lst;
}
int main()
{
vector<int> arr = { 12, 13, 1, 10, 34, 1 };
vector<int> res = print2Smallest(arr);
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
return 0;
}
Java
import java.util.*;
public class Main {
public static List<Integer>
print2Smallest(List<Integer> arr)
{
List<Integer> lst
= new ArrayList<>();
if (new HashSet<Integer>(arr).size()
== 1) {
return Arrays.asList(-1, -1);
}
lst.add(Collections.min(
arr));
int p = Collections.min(arr);
int c = Collections.frequency(
arr, p);
arr.removeAll(Collections.singleton(
p));
lst.add(Collections.min(
arr));
return lst;
}
public static void main(String[] args)
{
List<Integer> arr = new ArrayList<>(
Arrays.asList(12, 13, 1, 10, 34, 1));
List<Integer> res = print2Smallest(arr);
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i) + " ");
}
}
}
Python3
def print2Smallest(arr):
lst = []
if len(set(arr)) == 1:
return [-1, -1]
lst.append(min(arr))
p = min(arr)
c = arr.count(p)
for i in range(c):
arr.remove(p)
lst.append(min(arr))
return lst
arr = [12, 13, 1, 10, 34, 1]
print(print2Smallest(arr))
Javascript
function print2Smallest(arr) {
let lst = [];
if (new Set(arr).size === 1) {
return [-1, -1];
}
lst.push(Math.min(...arr));
let p = Math.min(...arr);
let c = arr.filter((el) => el === p).length;
for (let i = 0; i < c; i++) {
arr.splice(arr.indexOf(p), 1);
}
lst.push(Math.min(...arr));
return lst;
}
let arr = [12, 13, 1, 10, 34, 1];
console.log(print2Smallest(arr));
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
public static List<int> Print2Smallest(List<int> arr) {
List<int> lst = new List<int>();
if (new HashSet<int>(arr).Count == 1) {
return new List<int> {-1, -1};
}
lst.Add(arr.Min());
int p = arr.Min();
int c = arr.Count(x => x == p);
arr.RemoveAll(x => x == p);
lst.Add(arr.Min());
return lst;
}
public static void Main() {
List<int> arr = new List<int>{12, 13, 1, 10, 34, 1};
List<int> res = Print2Smallest(arr);
foreach (int i in res) {
Console.Write(i + " ");
}
}
}
Time Complexity: O(N)
Auxiliary Space: O(1)
Please write comments if you find any bug in the above program/algorithm or other ways to solve the same problem.
Last Updated :
13 Apr, 2023
Like Article
Save Article
Помогите =( Находится второе число, но совершенно другое, пробовал через отладчик найти, не могу понять в чем проблема.
int[] a = new int[] { 5, 12, 13, 2, 1, 9, 15, 19, 6 };
int oneMinValue = a[0];
int twoMinValue = a[0];
for (int i = 0; i < a.Length; i++)
{
if (oneMinValue > a[i])
{
oneMinValue = a[i];
}
else if (twoMinValue > a[i] & twoMinValue <= oneMinValue)
{
twoMinValue = a[i];
}
}
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(oneMinValue);
Console.WriteLine(twoMinValue);
}
Harry
214k15 золотых знаков117 серебряных знаков229 бронзовых знаков
задан 23 авг 2022 в 14:28
1
Вам надо не забывать, что инвариант — oneMinValue не превышает twoMinValue.
Так что вот как должно быть…
for (int i = 0; i < a.Length; i++)
{
if (twoMinValue > a[i])
{
twoMinValue = a[i];
}
if (twoMinValue < oneMinValue)
{
int tmp = twoMinValue;
twoMinValue = oneMinValue;
oneMinValue = tmp;
}
}
Ну и выводить в цикле совсем ни к чему:
Console.WriteLine(oneMinValue);
Console.WriteLine(twoMinValue);
Вот, смотрите результат.
Update
По замечанию DmitryK:
int oneMinValue = a[0];
int twoMinValue = a[1];
if (twoMinValue < oneMinValue)
{
int tmp = twoMinValue;
twoMinValue = oneMinValue;
oneMinValue = tmp;
}
for (int i = 2; i < a.Length; i++)
{
if (twoMinValue > a[i])
{
twoMinValue = a[i];
}
if (twoMinValue < oneMinValue)
{
int tmp = twoMinValue;
twoMinValue = oneMinValue;
oneMinValue = tmp;
}
}
ответ дан 23 авг 2022 в 14:35
HarryHarry
214k15 золотых знаков117 серебряных знаков229 бронзовых знаков
2
У вас условие никогда не выполняется.
if (twoMinValue > a[i] & twoMinValue <= oneMinValue)
Поскольку oneMinValue при проходе по массиву всегда является минимальным из уже встреченных чисел, то условие twoMinValue <= oneMinValue всегда ложное.
Должно быть что-то вроде такого:
int oneMinValue = a[0];
int twoMinValue = a[1];
if(oneMinValue > twoMinValue)
swap(oneMinValue, twoMinValue);
for (int i = 0; i < a.Length; i++)
if (oneMinValue > a[i])
{
twoMinValue = oneMinValue;
oneMinValue = a[i];
}
else
if(twoMinValue > a[i])
twoMinValue = a[i];
ответ дан 23 авг 2022 в 14:35
DmitryKDmitryK
4,4961 золотой знак5 серебряных знаков19 бронзовых знаков
|
Marod 21 / 1 / 0 Регистрация: 29.10.2015 Сообщений: 67 |
||||
|
1 |
||||
Два минимальных элемента массива21.12.2015, 22:36. Показов 8638. Ответов 5 Метки нет (Все метки)
Массив вещественный массив B(20). Не используя сортировку, найти два наименьших положительных числа.
0 |
|
Pikemaster 309 / 309 / 215 Регистрация: 24.09.2013 Сообщений: 771 |
||||
|
22.12.2015, 00:10 |
2 |
|||
P.S. Естественно первый элемент массива должен быть положительным, просто в коде я это никак не отразил, потому что способ формирования массива вы скрыли/не_указали, поэтому с теми фрагментами кода, которые вы не выложили — разбирайтесь сами.
0 |
|
Marod 21 / 1 / 0 Регистрация: 29.10.2015 Сообщений: 67 |
||||
|
24.12.2015, 10:31 [ТС] |
3 |
|||
|
ну почти
Добавлено через 8 часов 30 минут
0 |
|
kypiwindy 418 / 316 / 241 Регистрация: 29.05.2010 Сообщений: 796 Записей в блоге: 1 |
||||
|
24.12.2015, 19:56 |
4 |
|||
|
Marod,
0 |
|
Woldemar89 TheGreatCornholio 1249 / 727 / 285 Регистрация: 30.07.2015 Сообщений: 2,403 |
||||
|
24.12.2015, 20:21 |
5 |
|||
0 |
|
Psilon Master of Orion 6094 / 4950 / 905 Регистрация: 10.07.2011 Сообщений: 14,522 Записей в блоге: 5 |
||||
|
24.12.2015, 20:58 |
6 |
|||
|
Без допущения, что первый элемент массива положительный:
0 |
Оглавление:
- 1 Задача — Найти два наименьших (минимальных) элемента массива
— программирование на Pascal, Си, Кумир, Basic-256, Python- 1.1 Pascal
- 1.2 Язык Си
- 1.3 Python
- 1.4 КуМир
- 1.5 Basic-256
Задача — Найти два наименьших (минимальных) элемента массива
— программирование на Pascal, Си, Кумир, Basic-256, Python
В одномерном массиве целых чисел определить два наименьших элемента. Они могут быть как равны между собой (оба являться минимальными), так и различаться.
Сначала можно найти минимальный элемент массива. После этого искать второй минимум, исключив их поиска первый с помощью if. Данный способ рассматривается здесь по отношению к двум наибольшим элементам.
Сложнее задачу решить, используя один цикл перебора.
Предположим, что двумя наименьшими элементами массива являются первый и второй элемент. Присвоим их индексы переменным m1 и m2. При этом, если первый элемент меньше второго, то его индекс присвоим m1, иначе m1 получит значение второго элемента, а m2 первого.
Начнем перебирать массив в цикле, начиная с третьего элемента. Если он меньше элемента, чей индекс хранится в m1, то присвоим индекс текущего элемента m1. Иначе (если значение по индексу m1 меньше, чем по индексу i) будем проверять, не меньше ли значение по индексу i, того что по индексу m2.
Есть один не очевидный нюанс. Допустим, в m1 указывало на значение 5, а m2 — на 10. Очередной элемент равен 3. Мы меняем m1, и забываем о числе 5. Однако оно может оказаться как раз вторым минимумом массива.
Поэтому в программе при изменении значения m1 надо предусмотреть проверку, не меньше ли теряемое значение, чем то, что хранится по индексу m2.
Pascal
const
N = 10;
var
a: array[1..N] of integer;
i, min1, min2, buff: byte;
begin
randomize;
for i:=1 to N do begin
a[i] := random(100);
write(a[i]:4);
end;
writeln;
if a[1] < a[2] then begin
min1 := 1;
min2 := 2;
end
else begin
min1 := 2;
min2 := 1;
end;
for i:=3 to N do
if a[i] < a[min1] then begin
buff := min1;
min1 := i;
if a[buff] < a[min2] then
min2 := buff;
end
else
if a[i] < a[min2] then
min2 := i;
writeln(‘№’, min1:2,’: ‘, a[min1]:2);
writeln(‘№’, min2:2,’: ‘, a[min2]:2);
end. 8 66 40 40 0 14 50 74 93 71
№ 5: 0
№ 1: 8
Язык Си
#include <stdio.h>
#define N 10
main() {
int a[N];
int i, min1, min2, buff;
srand(time(NULL));
for (i=0; i<N; i++) {
a[i] = rand() % 100;
printf(«%3d», a[i]);
}
printf(«n»);
if (a[0] < a[1]) {
min1 = 0;
min2 = 1;
} else {
min1 = 1;
min2 = 0;
}
for (i=2; i<N; i++) {
if (a[i] < a[min1]) {
buff = min1;
min1 = i;
if (a[buff] < a[min2]) min2 = buff;
} else {
if (a[i] < a[min2]) min2 = i;
}
}
printf(«№%2d:%3dn»,min1+1,a[min1]);
printf(«№%2d:%3dn»,min2+1,a[min2]);
} 97 20 88 29 20 43 87 19 33 26
№ 8: 19
№ 5: 20
Python
from random import random
N = 10
a = []
for i in range(N):
a.append(int(random()*100))
print(«%3d» % a[i], end=»)
print()
if a[0] > a[1]:
min1 = 0
min2 = 1
else:
min1 = 1
min2 = 0
for i in range(2,N):
if a[i] < a[min1]:
b = min1
min1 = i
if a[b] < a[min2]:
min2 = b
elif a[i] < a[min2]:
min2 = i
print(«№%3d:%3d» % (min1+1, a[min1]))
print(«№%3d:%3d» % (min2+1, a[min2])) 14 3 40 56 42 43 89 69 64 72
№ 1: 14
№ 2: 3
КуМир
алг два минимальных
нач
цел N = 10
цел таб arr[1:N]
цел i,m1,m2,b
нц для i от 1 до N
arr[i] := irand(10,100)
вывод arr[i]:3
кц
вывод нс
если arr[1] < arr[2] то
m1 := 1
m2 := 2
иначе
m1 := 2
m2 := 1
все
нц для i от 3 до N
если arr[i] < arr[m1] то
b := m1
m1 := i
если arr[b] < arr[m2] то
m2 := b
все
иначе
если arr[i] < arr[m2] то
m2 := i
все
все
кц
вывод «№»,m1:2,»:»,arr[m1]:3,нс
вывод «№»,m2:2,»:»,arr[m2]:3,нс
кон 65 32 24 86 65 58 67 55 33 96
№ 3: 24
№ 2: 32
Basic-256
N = 10
dim arr(N)
for i=0 to N-1
arr[i] = int(rand*100)
print arr[i] + » «;
next i
print
if arr[0] < arr[1] then
m1 = 0
m2 = 1
else
m1 = 1
m2 = 0
endif
for i=2 to N-1
if arr[i] < arr[m1] then
b = m1
m1 = i
if arr[b] < arr[m2] then
m2 = b
endif
else
if arr[i] < arr[m2] then
m2 = i
endif
endif
next i
print (m1+1) + «: » + arr[m1]
print (m2+1) + «: » + arr[m2] 81 7 25 71 23 9 56 91 73 64
2: 7
6: 9
Did you find apk for android? You can find new Free Android Games and apps.

