Bubble Sort
Adjacent inversions swap करके sort करें।
Bubble Sort क्या है?
हर pass सबसे बड़ा unsorted value अंत तक भेजता है।
महत्वपूर्ण बातें
- Empty, single, duplicate और sorted input test करें।
- Correctness और optimization अलग रखें।
- Production में standard library को प्राथमिकता दें।
Bubble Sort Visualizer
O(n²)हर comparison और data movement देखने के लिए चलाएँ या अगला चरण दबाएँ।
C और C++ code examples
main.c
#include <stdio.h>
int main(void) {
int values[] = {5, 1, 4, 2};
for (int end = 3; end > 0; --end) {
int changed = 0;
for (int index = 0; index < end; ++index) {
if (values[index] > values[index + 1]) {
int temporary = values[index];
values[index] = values[index + 1];
values[index + 1] = temporary;
changed = 1;
}
}
if (!changed) break;
}
for (int index = 0; index < 4; ++index) {
printf("%d ", values[index]);
}
}
1 2 4 5
C++
main.cpp
#include <iostream>
#include <vector>
int main() {
std::vector values{5, 1, 4, 2};
for (auto end = values.end(); end != values.begin(); --end) {
bool changed = false;
for (auto item = values.begin(); item + 1 != end; ++item) {
if (*item > *(item + 1)) {
std::iter_swap(item, item + 1);
changed = true;
}
}
if (!changed) break;
}
for (int value : values) {
std::cout << value << ' ';
}
}
1 2 4 5
C और C++ की तुलना
यह learning के लिए है पर O(n²); early exit sorted input पर O(n), production C++ में सामान्यतः std::sort उपयोग होता है।
C
Loops, pointers, lengths और buffers स्पष्ट लिखे जाते हैं।
C++
Iterators और algorithms operation को storage से अलग करते हैं।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- हर comparison trace करें।
- Duplicates और extreme values test करें।
- Standard library के विरुद्ध benchmark करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज