fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. void twoPointerSort(vector<int>& arr) {
  6. int left = 0;
  7. int right = arr.size() - 1;
  8.  
  9. while (left < right) {
  10. if (arr[left] > arr[right]) {
  11. // Swap elements
  12. int temp = arr[left];
  13. arr[left] = arr[right];
  14. arr[right] = temp;
  15. }
  16. // Move pointers
  17. left++;
  18. right--;
  19. }
  20. }
  21.  
  22. int main() {
  23. vector<int> arr = {5, 2, 8, 2, 1};
  24.  
  25. cout << "Original array: ";
  26. for (int num : arr) {
  27. cout << num << " ";
  28. }
  29. cout << endl;
  30.  
  31. twoPointerSort(arr);
  32.  
  33. cout << "Sorted array: ";
  34. for (int num : arr) {
  35. cout << num << " ";
  36. }
  37. cout << endl;
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0.01s 5272KB
stdin
Standard input is empty
stdout
Original array: 5 2 8 2 1 
Sorted array: 1 2 8 2 5