C 不改变顺序,原址剔除数组中的0元素

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <time.h>

#define NUM_CNT 10000000
#define FILE_NAME "num.txt"

void genNumber()
{
    int i = 0;
    int *arr = (int*)malloc(sizeof(int) * NUM_CNT);
    for(;i < NUM_CNT; ++i)
    {
        arr[i] = i;
    }
    FILE *fp = fopen(FILE_NAME,"w");
    if(NULL == fp){printf("open %s failed\n",FILE_NAME);}
    for(i = 0;i < NUM_CNT; ++i)
    {
        if(i%7 == 0){arr[i] = 0;}
        fprintf(fp,"%d ",arr[i]);
    }
    fclose(fp);
}

void readNum(int arr[])
{
    int i = 0;
    FILE *fp = fopen(FILE_NAME,"r");
    if(NULL == fp){printf("open %s failed\n",FILE_NAME);}
    for(i = 0;i < NUM_CNT; ++i)
    {
        fscanf(fp,"%d ",&arr[i]);
    }
    fclose(fp);
}

void dump(int *arr)
{
    int i = 0;
    for(i = 0;i < NUM_CNT; ++i)
    {
        printf("%d ",arr[i]);
    }
    printf("\n");
}

void del(int *arr,int len)
{
    int i = 0,j = 0,t = 0;
    for(; i < len - 1; ++i)
    {
        if(arr[i] == 0)
        {
            j = i + 1;
            while(j < len && arr[j]==0)++j;
            if(j < len)
            {
                t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;
            }
        }
    }
}

void del1(int *arr,int len)
{
    int i = 0,j = 0,t = 0;
    while(j < len && arr[j]==0)++j;
    if(j == len )return;
    for(; i < len - 1 && j < len; ++i)
    {
        if(arr[i] == 0)
        {
            t = arr[i];
            arr[i] = arr[j];
            arr[j] = t;
            while(j < len && arr[j]==0)++j;
        }
    }
}

int main()
{
    int t = 0;
    int *arr= (int*)malloc(sizeof(int) * NUM_CNT);
    genNumber();
    readNum(arr);
    //dump(arr);
    t = clock();
    del1(arr,NUM_CNT);
    printf("use time:%lu ms\n",clock() - t);
    //dump(arr);
    return 0;
}

 

posted @ 2016-08-19 09:37  你好阿汤哥  Views(339)  Comments(0Edit  收藏  举报