Website Summary Files Commits Branches @commit @diff @stats
path: root / pract_SI / Pract. 05 / Solutions / task2_bonus.cpp
blob: 5d56134f409fbd5c4f88dd6bb81b4d7f42d992a5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>

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

void resetChanges(int &index,bool &changesOccured)
{
	index = -1;
	changesOccured = false;
}

bool changeCurrentIndex(int index, int &currentIndex)
{
	return currentIndex = index;
}

void sortNumbers(int *arr, size_t size)
{
	int counter = NULL, min, max, currentIndex;
	bool sortingEvenNumbers = true, changeOccured;

	do
	{
		if (sortingEvenNumbers)
			min = INT_MAX; //reset min
		else
			max = INT_MIN; //reset max

		resetChanges(currentIndex, changeOccured);//reset change flag & index

		for (size_t i = counter; i < size; i++)
		{
			if (sortingEvenNumbers)
			{
				if (arr[i] % 2 == 0 && arr[i] < min)
				{
					min = arr[i];
					changeOccured = changeCurrentIndex(i, currentIndex);
				}
			}
			else
			{
				if (arr[i] % 2 != 0 && arr[i] > max)
				{
					max = arr[i];
					changeOccured = changeCurrentIndex(i, currentIndex);
				}
			}
		}

		if (!changeOccured && sortingEvenNumbers)
		{
			sortingEvenNumbers = !sortingEvenNumbers;
			changeOccured = true;
		}
		else if(changeOccured)
		{
			swap(arr[counter], arr[currentIndex]);
			counter++;
		}
	}while(changeOccured);
}