December 23, 2024
Moving Zeros To The End

Belajar Bahasa C – Moving Zeros To The End

Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. The problem link is here.

Examples:

move_zeros(10, int [] {1, 2, 0, 1, 0, 1, 0, 3, 0, 1}); // -> int [] {1, 2, 1, 1, 3, 1, 0, 0, 0, 0}

Sample Tests:

Test(move_zeros, sample_tests) {
    do_test(8, ((int []) {0, 1, 0, 2, 0, 3, 4, 5}), ((int []) {1, 2, 3, 4, 5, 0, 0, 0}));
    do_test(20, ((int []) {9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9}), ((int []) {9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}));
    do_test(2, ((int []) {0, 0}), ((int []) {0, 0}));
    do_test(1, ((int []) {0}), ((int []) {0}));
    do_test(0, ((int []) {}), ((int []) {}));
}

Solution:

#include <stddef.h>

void move_zeros(size_t len, int arr[len])
{
  // mutate arr in place
  size_t i, j, k, temp;
  for (i = 0; i < len; i++)
  {
    if (arr[i] == 0)
    {
      k = i;
      for (j = i + 1; j < len; j++)
      {
        if (arr[j] != 0)
        {
          temp = arr[j];
          arr[j] = 0;
          arr[k] = temp;
          k = j;
        }
      }
    }
  }
}

Rajo Intan

Blogger, pemiliki Onestring Lab, menulis artikel terkait teknologi informasi dan pendidikan. Web Developer, berpengalaman lebih dari 20 tahun mengembangkan berbagai aplikasi dan sistem informasi. Kerjasama kontak di onestringlab@gmail.com atau https://forms.gle/xAGKkpi6B3BzJyzk7

View all posts by Rajo Intan →

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
100% Free SEO Tools - Tool Kits PRO