প্রোগ্রামিং-এ সর্টিং একটি মৌলিক ফাংশন যা ডেটাকে আরোহী বা অবরোহী ক্রমে সাজায়। C++-এ <algorithm> হেডারের std::sort() ফাংশন দিয়ে সহজে অ্যারে বা কন্টেইনার সর্ট করা যায়।
সিনট্যাক্স:
sort(start_address, end_address)
- Start address – প্রথম উপাদানের ঠিকানা (যেমন
aবাa+0) - End address – শেষ উপাদানের পরবর্তী লোকেশনের ঠিকানা (যেমন
a+5৫ উপাদানের জন্য)
উদাহরণ কোড
#include <iostream>
#include <algorithm>
using namespace std;
void display(int a[]) {
for (int i = 0; i < 5; ++i)
cout << a[i] << " ";
}
int main() {
int a[5] = {4, 2, 7, 9, 6};
cout << "\nThe array before sorting is: ";
display(a);
sort(a, a + 5); // ডিফল্ট: আরোহী ক্রম (ascending)
cout << "\n\nThe array after sorting is: ";
display(a);
return 0;
}
আউটপুট
The array before sorting is: 4 2 7 9 6 The array after sorting is: 2 4 6 7 9
অতিরিক্ত জানুন:
- নিম্নক্রমে (descending) সর্ট:
sort(a, a+5, greater<int>()); - কাস্টম কমপ্যারেটর:
sort(v.begin(), v.end(), [](int x, int y){ return x > y; }); std::sortইন্ট্রোসর্ট (Introsort) ব্যবহার করে — O(n log n) গ্যারান্টি।- স্ট্রিং, ভেক্টর, ডিক — সব जगह একই সিনট্যাক্স কাজ করে।