Can someone help me identify the sorting algorithm I coded?

0
5
Asked By TechWanderer47 On

I wrote some code in C++ that sorts an array, but I'm not sure what sorting algorithm it actually implements. Here's my code:
```cpp
#include
#include
#include

int main() {
int i{};
int z{};
std::vector arr = {3,2,1,24,5,2,4,3,6,7};
for (i = 0; i < std::size(arr); i++) {
for (z = i + 1; z arr[z])
std::swap(arr[i], arr[z]);
}
for (i = 0; i < std::size(arr); i++)
std::cout << arr[i] << std::endl;
}
```

3 Answers

Answered By NerdyNina On

Honestly, coding without knowing exactly what you've written is just part of the learning process! Keep experimenting and debugging. If you aim for bubble sort, try to work through the logic step by step to make sure it sorts correctly as you intended.

Answered By CodeExplorer77 On

Don't worry, it happens to the best of us! If you're experimenting, it's actually a great way to learn. It sounds like you intended to code bubble sort, but it kind of ended up being more like selection sort. You just need to refine the logic a bit.

Answered By CodeGuru2020 On

It looks like you might have written something resembling bubble sort, but there are some issues with how it's implemented. Your approach is swapping elements in a way that doesn’t ensure the entire array gets sorted correctly. If the array is out of order enough, it won't sort completely.

CuriousCoder89 -

If you were aiming for bubble sort, you might want to add a way to check if any swaps were made in the last pass, to avoid unnecessary iterations once the array is sorted.

BoringBot313 -

Have you considered using the `std::sort()` function from the algorithm header? It's a lot simpler!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.