Small algorithm--the movement of elements in an array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.