Created
October 20, 2021 13:36
-
-
Save coderodde/6c327b731fd830e829c142b3ec2ae268 to your computer and use it in GitHub Desktop.
CodeReview answer for funny arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
// Modifies array! | |
int numberOfTimes(int array[], int n) { | |
int count = 0; | |
int flag = 0; | |
int sizeCounter = 0; | |
while (true) { | |
for (int i = 0; i < n - 1; ++i) { | |
if (array[i] <= array[i + 1]) { | |
sizeCounter++; | |
array[sizeCounter] = array[i + 1]; | |
} | |
else { | |
flag = 1; | |
} | |
} | |
if (flag == 0) | |
return count; | |
count++; | |
flag = 0; | |
n = (sizeCounter + 1); | |
sizeCounter = 0; | |
} | |
} | |
// Modifies array! | |
size_t numberOfTimes2(int array[], size_t n) { | |
size_t count = 0; | |
while (true) { | |
size_t sizeCounter = 0; | |
bool flag = false; | |
for (size_t i = 0; i < n - 1; ++i) { | |
if (array[i] <= array[i + 1]) { | |
array[++sizeCounter] = array[i + 1]; | |
} | |
else { | |
flag = true; | |
} | |
} | |
if (!flag) { | |
return count; | |
} | |
count++; | |
n = sizeCounter + 1; | |
} | |
} | |
int main() { | |
int ar[] { 10, 9, 7, 8, 6, 5, 3, 4, 2, 1, 3, 5 }; | |
int ar2[]{ 10, 9, 7, 8, 6, 5, 3, 4, 2, 1, 3, 5 }; | |
std::cout << numberOfTimes(ar, sizeof(ar) / sizeof(ar[0])) << "\n"; | |
std::cout << numberOfTimes2(ar2, sizeof(ar2) / sizeof(ar2[0])) << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment