zoukankan      html  css  js  c++  java
  • 据说是淘宝面试题“给定一个数组将大于0的放在最右边,等于0的放在中间,大于0的放在最左边”

    给定一个数组将大于0的放在最右边,等于0的放在中间,大于0的放在最左边;

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <time.h>
     4 #define random (rand()%10-5)
     5 void swap(int *a, int *b)//交换两个整型数
     6 {
     7     int t = *a;
     8     *a = *b;
     9     *b = t;
    10 }
    11 
    12 void move_array(int a[], int n)
    13 {
    14     int *low = a, *high = a + n-1;
    15     while(low < high)
    16     {
    17         while(*low < 0 && low < high) low++;
    18         while(*high > 0 && high > low) high--;
    19         if(low < high)
    20             swap(low, high);
    21     }
    22     //循环结束后low一定等于high且指向大于等于0的数
    23     //第二步,从low开始,将等于0得数移到左边
    24     high = a + n-1;
    25     while(low < high)
    26     {
    27         while(*low == 0 && low < high) low++;
    28         while(*high > 0 && high > low) high--;
    29         if(low < high)
    30             swap(low, high);
    31     }
    32 }
    33 int main()
    34 {
    35     srand(time(NULL));
    36     int a[10];
    37     int i;
    38     for(i = 0; i < 10; i++)
    39     {
    40         a[i] = random;
    41     }
    42     move_array(a, 10);
    43     for(i = 0; i < 10; i++)
    44     {
    45         printf("%-5d", a[i]);
    46     }
    47     printf("
    ");
    48 
    49     return 0;
    50 }
  • 相关阅读:
    git 常用命令
    PHP打印日志类
    如何从总账获取分类账信息
    AP -> GL 数据流动
    JDeveloper 速度慢问题
    JDeveloper 滚轮不受控制
    MyBatis 环境搭建
    初识 MyBatis
    Linux 中设置 MySQL 字符集为 UTF-8
    Linux 安装 MySQL 详解(rpm 包)
  • 原文地址:https://www.cnblogs.com/xuyh/p/3334530.html
Copyright © 2011-2022 走看看