Answer the question
In order to leave comments, you need to log in
How many times does the first element change its place?
I can't understand at the end, in the comment in the code I wrote that I don't understand, can you please explain)
The array is sorted by the selection method in ascending order (from left to right: the minimum is searched and changes with the left element). How many times does the first element change its place?
Specifications Input
The first line contains one natural number n — the number of elements in the array ( 1 ≤ n ≤ 1000 ). The second line contains the array itself of n natural numbers. It is guaranteed that all numbers are different and do not exceed 10 6 .
Output
Output a single number — the number of moves of the first element.
Examples
input
3
1 3 2
output
0
input
4
4 1 5 3
output
3
import java.util.Scanner;
public class Sortirovka4 {
public static void main(String[] args) {
int counter, num;
Scanner input = new Scanner(System.in);
System.out.println("Введите количество элементов массива: ");
num = input.nextInt();
int[] array = new int[num];
System.out.println("Введите " + num + " чисел");
//Заполняем массив, вводя элементы в консоль
for (counter = 0; counter < num; counter++) {
array[counter] = input.nextInt();
}
// сортируем массив
selectionSort(array);
}
static void selectionSort(int[] a) {
int N = a.length;
int count = 0;
int first = a[0];
for (int i = 0; i < N - 1; i++) {
int min = i;
for (int j = i + 1; j < N; j++) {
if (a[j] < a[min]) {
min = j;
}
}
int t = a[min];
a[min] = a[i];
a[i] = t;
if (a[i] == first || a[min] == first) { //по идее здесь должен быть a[j] == first,
count++; //но я не могу понять, как это реализовать
}
}
System.out.println(count);
}
}
Answer the question
In order to leave comments, you need to log in
Generic method (elements can be repeated. For example: {4,1,3,8,4}).
There will be questions, write in the comments.
static void selectionSort(int[] a) {
int size = a.Length;
int numb = 0; //Номер текущего индекса первого элемента
int count = 0;
for (int i = 0; i < size - 1; i++)
{
int min = i;
for (int j = i + 1; j < size; j++)
{
if (a[j] < a[min])
{
//Тут отслеживаем изменение индекса первого элемента
if (min == numb)
{
numb = j;
count++;
}
else
{
if (j == numb)
{
numb = min;
count++;
}
}
min = j;
}
}
int t = a[min];
a[min] = a[i];
a[i] = t;
}
System.out.println(count);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question