এই প্রোগ্রামে C++ STL-এ list কন্টেইনারের সর্টিং ফাংশনালিটি বাস্তবায়ন করা হয়েছে। list একটি সিকোয়েন্স কন্টেইনার যা নন-কন্টিগুয়াস মেমরি অ্যালোকেশন অনুমতি দেয়।
ব্যবহৃত ফাংশন ও বর্ণনা:
- l.push_back() – লিস্টের শেষে উপাদান যোগ করে।
- l.sort() – লিস্টের উপাদানগুলো সাজায় (ডিফল্টভাবে আরোহী ক্রমে)।
উদাহরণ কোড
#include <iostream>
#include <list>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
list<int> l;
list<int>::iterator it;
int choice, value;
while (true) {
cout << "1. Insert Element to the list" << endl;
cout << "2. Display the List (Sorted)" << endl;
cout << "3. Exit" << endl;
cout << "Enter your Choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to be inserted: ";
cin >> value;
l.push_back(value);
break;
case 2:
l.sort(); // লিস্ট সর্ট করা
cout << "Elements of the List: ";
for (it = l.begin(); it != l.end(); ++it)
cout << *it << " ";
cout << endl;
break;
case 3:
exit(0);
default:
cout << "Wrong Choice" << endl;
}
}
return 0;
}
নমুনা আউটপুট
1. Insert Element to the list 2. Display the List 3. Exit Enter your Choice: 1 Enter value to be inserted: 7 ... Enter your Choice: 2 Elements of the List: 4 6 7 10 Enter your Choice: 3 Exit code: 1
দ্রষ্টব্য: list::sort() মার্জ সর্ট অ্যালগরিদম ব্যবহার করে যা O(n log n) টাইম কমপ্লেক্সিটি দেয়। এটি লিস্টের নোডগুলোকে রি-লিংক করে সর্ট করে, উপাদানগুলো কপি বা মুভ করে না।