zoukankan      html  css  js  c++  java
  • 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
    ",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
    ",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("
    ");
    }
    
    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
    ",clock() - t);
        //dump(arr);
        return 0;
    }
  • 相关阅读:
    机器学习理解
    如何让Vim成为我们的神器
    新一代 Linux 文件系统 btrfs 简介 【转载】
    第一次写Linux下Makefile的笔记
    UEFI boot sequence
    #pragma pack
    Linux makefile sample
    解决ScrollView中嵌套ListView滚动效果冲突问题
    Android SqLite升级
    Android 播放gif图片
  • 原文地址:https://www.cnblogs.com/tangxin-blog/p/5786365.html
Copyright © 2011-2022 走看看