fork download
  1. #include <iostream>
  2. #include <list>
  3.  
  4. using namespace std;
  5.  
  6. void sort_list(list<int>& a)
  7. {
  8. //from the first until the pre-last element
  9. for(list<int> :: iterator itr = a.begin(); itr != (--a.end()); ++itr)
  10. {
  11. int* smallest = &(*itr);
  12.  
  13. //get smallest element after current index
  14. list<int> :: iterator itr2 = itr;
  15. for(++itr2; itr2 != a.end(); ++itr2)
  16. {
  17. if (*smallest > *itr2)
  18. {
  19. smallest = &(*itr2);
  20. }
  21. }
  22. //swap smallest and current index
  23. int tmp = *itr;
  24. *itr = *smallest;
  25. *smallest = tmp;
  26. }
  27. }
  28.  
  29. int main()
  30. {
  31. //create a list and some elements
  32. list<int> listi;
  33. listi.push_back(5);
  34. listi.push_back(4);
  35. listi.push_back(3);
  36. listi.push_back(2);
  37. listi.push_back(1);
  38.  
  39. // sort the list
  40. sort_list(listi);
  41. //print all of the elements
  42. for(list<int> :: iterator itr = listi.begin(); itr != listi.end(); ++itr)
  43. {
  44. cout << *itr << endl;
  45. }
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 2984KB
stdin
Standard input is empty
stdout
1
2
3
4
5