@Muriam

Как корректно вывести на экран кол-во пересылок и сравнений в пузырьковой сортировке массива?

Как сделать чтоб кол-во сравнений и пересылок отображались после отсортированного пузырьком массива,
а не между надписью "пузырьковая сортировка" и последовательностью "0 24 34 41 58 62 64 67 69 78"?
Текущий вывод:
5ca17ff4bba33697437723.png
#include <iostream>
#include <cstdlib>
#include <locale>
#include <conio.h>
#define SIZE 10

using namespace std;

void random_array(int array[SIZE]);
void bubble_sort(int array[SIZE]);
void select_sort(int array[SIZE]);
void shaker_sort(int array[SIZE]);


int main() 
{
    setlocale(LC_ALL, "rus");
    
    int array[SIZE];
      
    random_array(array);    
    bubble_sort(array); 
    for (int i = 0; i <= SIZE-1; i++) 
        cout << array[i] << " ";
    cout << "\n\n";

    random_array(array);
    select_sort(array); 
    for (int i = 0; i <= SIZE-1; i++) 
        cout << array[i] << " ";
    cout << "\n\n";
    
    random_array(array);
    shaker_sort(array);
    for (int i=0; i <= SIZE-1; i++)
        cout << array[i] << " ";
    cout << "\n\n";
    
     
    getch();
    return 0;
}

void random_array(int array[SIZE])
{
    cout << "исходный массив" << endl;
    for (int i=0; i<SIZE; i++) 
    {
        array[i] = rand()%100;
        cout << array[i] << " ";
    }
}

void bubble_sort(int array[SIZE])
{
    int comparison = 0;
    int transfer = 0;
    
    cout << "\nпузырьковая сортировка" << endl;       
    for (int i = 0; i < SIZE-1; i++)
	{
	 
        for (int j = SIZE-2; j >= i; j--)
        {
        	comparison++;						  // инкремент сравнений
			if (array[j] > array[j+1])                              // если предыдущий элемент больше следующего
			{
				int temp = array[j];                           //
                                array[j] = array[j+1];                         // меняю их местами
				array[j+1] = temp;                            //
				transfer++;				        // инкремент пересылок
			}
		}
	}
		
    cout << "сравнений " << comparison << endl;
    cout << "пересылок " << transfer << endl;
}

void select_sort(int array[SIZE])
{    
    int min, temp;
    cout << "\nсортировка методом прямого выбора" << endl;       
	for (int i = 0; i < SIZE-1; i++) 
	{ 
	    min = i;                                                                // индекс минимального элемента
	    for (int j = i+1; j < SIZE; j++) 
	        if (array[ j ] < array[min])                                // если текущий элемент меньше минимального
                {           
		    	min = j;                                                  // запоминаю его индекс
                }                  
	    temp = array[i];                                                 //
	    array[i] = array[min];                                        // меняю их местами
	    array[min] = temp;                                           //
	}
}

void shaker_sort(int array[SIZE])
{
    int left, right, border, temp;    
    cout << "\nшейкерная сортировка" << endl;
	for (right=SIZE-1, left=0, border=-1; border!=0;)    // устанавливаю правую и левую границы
	{
	    border = 0;
	    for (int i=left; i<right; i++)                                 // двигаюсь слева направо
	    {
	        if (array[i] > array[i+1])                                 // если текущий элемент больше следующего
		{ 
		    	temp = array[i];               	            // 
	        	array[i] = array[i+1];                            // меняю их местами
		    	array[i+1] = temp;                               //
		    	border = i;                                          // устанавливаю метку последней перестановки 
		}
	    }   
		right = border;                                          // запоминаю правую границу
		for (int i=right; i>left; i--)                         // двигаюсь справа налево
		{
		    if (array[i-1] > array[i])                        // если текущий элемент меньше следующего
		    {
		        temp = array[i];                              // 
			array[i] = array[i-1];                       // меняю их местами
			array[i-1] = temp;	           	     //
			border = i;                    	             // устанавливаю метку последней перестановки
		    }
		}
		left = border;                           // запоминаю границу
	}
}
  • Вопрос задан
  • 193 просмотра
Решения вопроса 2
mrjbom
@mrjbom
У тебя сначала вызывается функция в которой и выводятся эти данные и после её завершения выводится сам массив.

1. Вынести cout'ы в функцию main и сделать переменные считающие данные в глобальную область.
2. Передавать 2 перемененные в функцию по ссылке и затем в main'e выводить после вывода массива.
3. Выводить массив в функции.
Ответ написан
myjcom
@myjcom Куратор тега C++
Как-то так:
#include <iostream>
#include <map>
#include <string>
#include <iomanip>
using namespace std;


void swap(int& a, int& b)
{
  int c = a;
  a = b;
  b = c;
}

struct info
{
  int swapCount = 0;
  int compCount = 0;
};

class Counter
{
  public:
    static Counter& Instance()
    {
      static Counter tsCounter;
      return tsCounter;
    }

    info& getCount(string fn)
    {
      return callCount[fn];
    }

    void print()
    {
      for(auto& a : callCount)
      {
        cout << a.first   << "\n"
             << setw(15) << left << "swap: " << a.second.swapCount << "\n"
             << setw(15) << left << "compare: " << a.second.compCount << "\n";
      }
      cout.flush();
    }

  private:
    map<string, info> callCount;
    Counter(){}
    Counter(const Counter&) = delete;
    Counter& operator=(const Counter&) = delete;
};

void mysort(int* a, size_t sz)
{
  for(int i = 0; i < sz - 1; ++i)
  {
    int minIdx = i;
    for(int j = i + 1; j < sz; ++j)
    {
      if(a[j] < a[minIdx]) minIdx = j;
    }
    swap(a[i], a[minIdx]);
    Counter::Instance().getCount(__FUNCTION__).swapCount++;
  }
}


int main()
{
  int a[] = {2, 5, 6, 77, 1, 32, 45, 77, 12, 13, 14, 15};
  mysort(a, sizeof(a)/sizeof(int));
  Counter::Instance().print();
}

Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы