fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void swap(int& a, int& b) {
  5. int tmp = a;
  6. a = b;
  7. b = tmp;
  8. }
  9.  
  10. void partition(int* arr, int n, int k) {
  11. int pivot = 0, i = -1;
  12.  
  13. for (int j = 0; j < n; ++j) {
  14. // If current element is smaller than the pivot
  15. if (arr[j] <= pivot) {
  16. i++; // increment index of smaller element
  17. swap(arr[i], arr[j]);
  18. }
  19. }
  20.  
  21. if (k != -1)
  22. swap(arr[i + 1], arr[k]);
  23. }
  24.  
  25. int moveZero(int* arr, int n) {
  26. int zero_pos = n - 1;
  27. int cnt = 0;
  28.  
  29. while (arr[zero_pos] == 0)
  30. zero_pos--;
  31.  
  32. for (int i = 0; i <= zero_pos; ++i)
  33. if (arr[i] == 0) {
  34. ++cnt;
  35. swap(arr[i], arr[zero_pos]);
  36. --zero_pos;
  37. }
  38.  
  39. return (cnt > 0) ? zero_pos + 1: -1;
  40. }
  41.  
  42. void output(int* arr, int n) {
  43. for (int i = 0; i < n; ++i)
  44. cout << arr[i] << " ";
  45. }
  46.  
  47. int main() {
  48. int a[] = {4, 0, -1, 3, 5, 2, 1, 0, -3, 2, 0}; // trường hợp có nhiều số 0
  49. // int a[] = {4, 0, -1, 3, 5, 2, 1, -3, 2}; // trường hợp không có duy nhất một số 0
  50. // int a[] = {4, -1, 3, 5, 2, 1, -3, 2}; // trường hợp không có số 0
  51. int n = sizeof(a) / sizeof(a[0]);
  52.  
  53. int k = moveZero(a, n);
  54. partition(a, n, k);
  55. output(a, n);
  56. cout << "\n";
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
-1   -3   0   0   0   4   1   2   2   3   5