Title Description: Given an array, assume that the array is more than 0, and that the other elements appear once,
Try to move all 0 to the tail of the array.
Example:
Given array: 1,3,0,5,7,0,3,4
Last obtained array: 1,3,5,7,3,4,0,0
Here are two ways to achieve:
Method One: The principle is that when encountering 0, the elements behind the unification move forward. If the front is a 0, the rear element
Move forward one, if two 0, the rear element moves forward 2, and so on, and finally fills the back element with the
0.
Code implementation:
#include <stdio.h>void movezeros (int arr[], int len) {if (len <= 0) {return;} int i = 0;int Zeros = 0;for (i = 0;i < Len; i++) {if (arr[i]! = 0) {Arr[i-zeros] = arr[i];} else{zeros++;}} for (i = Len-zeros;i < len;i++) {Arr[i] = 0;}} int main () {int arr[8] = {1,3,0,7,8,0,2,9};movezeros (arr,8); int i = 0;for (i = 0;i < 8; i++) {printf ("%d", Arr[i]);} System ("pause"); return 0;}
Method Two:
Code implementation:
#include <stdio.h>void moveZeros2 (int arr[], int len) {if (len <= 0) {return;} int i = 0;int tmp = 0;int j = 0;for (i = 0;i < Len; i++) {if (arr[i]! = 0) {tmp = Arr[i];arr[i] = arr[j];arr[j] = tmp;j++ ;}}} int main () {int arr[8] = {1,3,0,7,8,0,2,9};movezeros2 (arr,8); int i = 0;for (i = 0;i < 8; i++) {printf ("%d", Arr[i]);} System ("pause"); return 0;}
Of course, there are other ways to solve this problem, for example, the non-0 element behind the array and the 0 interchange in front of the group.
But it feels like the top method is 2 efficient.
All right, let's get this sorted.
Small algorithm--the movement of elements in an array