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