Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.2 kB
3
Indexable
Прямой выбор

#include <iostream>
 
using namespace std;

int comparisons = 0;
int permutations = 0;

void selection(int *arr, int size)
{
  int min, temp;
  for (int i = 0; i < size - 1; i++) 
  {
    min = i; 
    for (int j = i + 1; j < size; j++)
    {
      if (arr[j] < arr[min]) 
        {
        min = j;
        comparisons += 1;
        }
        else{
        comparisons += 1;}
        
    }
        
    temp = arr[i];
    arr[i] = arr[min];
    arr[min] = temp;
    
    permutations += 1;
  }
}
 
int main()
{
    int arr[20] = {20, 1, 19, 2, 18, 3, 17, 4, 16, 5, 15, 6, 14, 7, 13, 8, 12, 9, 11, 10};
    
    cout << "Массив ДО сортировки прямым выбором:" << endl;

    for (int i = 0; i < 20; i++)
    {
     cout << arr[i] << " "; 
    }
    
    cout << endl << endl;
    
    cout << "Массив ПОСЛЕ сортировки прямым выбором:" << endl;
    
    selection(arr, 20);
    for (int i = 0; i < 20; i++)
    {
     cout << arr[i] << " "; 
    }
  
    cout << endl << endl;
     
    cout << "перестановки - " << permutations << endl;
    cout << "сравнения - " << comparisons << endl;
    
    return 0;
}