diff options
Add task2 solutions
2 files changed, 93 insertions, 0 deletions
| -rw-r--r-- | pract_SI/Pract. 05/Solutions/task2.cpp | 27 | ||||
| -rw-r--r-- | pract_SI/Pract. 05/Solutions/task2_bonus.cpp | 66 |
diff --git a/pract_SI/Pract. 05/Solutions/task2.cpp b/pract_SI/Pract. 05/Solutions/task2.cpp new file mode 100644 index 0000000..0d48adc --- /dev/null +++ b/pract_SI/Pract. 05/Solutions/task2.cpp @@ -0,0 +1,27 @@ +void swap(int &a, int &b) +{ + int temp = a; + a = b; + b = temp; +} + +void sortNumbers(int *arr, size_t size) +{ + int leftNumber = 0, rightNumber = size - 1; + + while (leftNumber < rightNumber) + { + while (arr[leftNumber] % 2 == 0 && leftNumber < rightNumber) + leftNumber++; + + while (arr[rightNumber] % 2 == 1 && leftNumber < rightNumber) + rightNumber--; + + if (leftNumber < rightNumber) + { + swap(arr[leftNumber], arr[rightNumber]); + leftNumber++; + rightNumber--; + } + } +}
\ No newline at end of file diff --git a/pract_SI/Pract. 05/Solutions/task2_bonus.cpp b/pract_SI/Pract. 05/Solutions/task2_bonus.cpp new file mode 100644 index 0000000..5d56134 --- /dev/null +++ b/pract_SI/Pract. 05/Solutions/task2_bonus.cpp @@ -0,0 +1,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 ¤tIndex) +{ + 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); +} |
