A
A
Archpriest Metapop2020-08-13 12:22:32
C++ / C#
Archpriest Metapop, 2020-08-13 12:22:32

Sorting an array using the direct selection method does not work. What to do?

The array arr is entered from the keyboard and consists of a elements.

//вставка_1//
        //тут мы задаём основые условия: выполнения и переходв //
        for (int starti = 0; starti < a - 1; starti=starti+1)

        {
            //тут мы принимаем навчальное значение за минимальное//
            int mini = starti;
            //тут мы ищем //
            for (int currentIndex = starti + 1; currentIndex < a; currentIndex = currentIndex + 1)
            {
                if (arr[currentIndex] < arr[mini])
                    mini = currentIndex;
            }
            std::swap(arr[starti], arr[mini]);
        }
        for (int i = 0; i < a; i=i+1)
        std::cout << arr[i] << ' ';
        return 0;


Where did I make a mistake?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Solomennikov, 2020-08-13
@caramel14

Here is an example using vector, the input works while INTEGER numbers are entered, for example, if the number 3.5 is entered, then 3 will fall into vector, the fractional part will be discarded, and the rest of the input will also be discarded, even if there are INTEGER numbers.

#include <iostream>
#include <vector>

int main() {

  std::vector<int> arr;
  int n;

  std::cout << "Enter numbers: ";

  while(std::cin >> n)
    arr.push_back(n);
  
    for (int starti = 0, mini, len = arr.size(); starti < len-1; starti++) {
        // тут мы принимаем начальное значение за минимальное//
        mini = starti;

        // тут мы ищем //
        for (int currentIndex = starti+1; currentIndex < len; currentIndex++) {
            if (arr[currentIndex] < arr[mini])
                mini = currentIndex;
        }

        std::swap(arr[starti], arr[mini]);
    }

    for (int i = 0, len = arr.size(); i < len; i=i+1)
    	std::cout << arr[i] << ' ';
    	
    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question