zoukankan      html  css  js  c++  java
  • 剑指Offer12 数组奇数调整至偶数前

     1 /*************************************************************************
     2     > File Name: 12_ReorderArray.c
     3     > Author: Juntaran
     4     > Mail: JuntaranMail@gmail.com
     5     > Created Time: 2016年08月30日 星期二 15时15分42秒
     6  ************************************************************************/
     7 
     8 #include <stdio.h>
     9 #include <stdlib.h>
    10 
    11 // 所有奇数放在偶数前面
    12 void ReorderOddEven(int* nums, int length)
    13 {
    14     if (length <= 0)
    15         return;
    16     
    17     int left  = 0;
    18     int right = length - 1;
    19     
    20     while (left < right)
    21     {
    22         // 从左向右找第一个偶数
    23         while (nums[left] % 2 != 0)
    24             left ++;
    25         
    26         // 从右向左找第一个奇数
    27         while (nums[right] %2 == 0)
    28             right --;
    29         
    30         if (left < right)
    31         {
    32             int temp = nums[left];
    33             nums[left]  = nums[right];
    34             nums[right] = temp;
    35         }
    36     }
    37 }
    38 
    39 void PrintNums(int* nums, int length)
    40 {
    41     for (int i = 0; i < length; ++i)
    42         printf("%d ", nums[i]);
    43     
    44     printf("
    ");
    45 }
    46 
    47 int main()
    48 {
    49     int nums[] = {1, 2, 3, 4, 5, 6};
    50     int length = 6;
    51     
    52     PrintNums(nums, length);
    53     ReorderOddEven(nums, length);
    54     PrintNums(nums, length);
    55     
    56     return 0;
    57 }
  • 相关阅读:
    css基础面试题
    hack-checkbox
    装饰性属性
    【CF809E】Surprise me!
    [SCOI2012]奇怪的游戏
    [HAOI2018]奇怪的背包
    CF1139D Steps to One
    [CTSC2018]假面
    写在省选前
    [SDOI2015]寻宝游戏
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5823149.html
Copyright © 2011-2022 走看看