算法学习---求数组中的最大数

来源:互联网 发布:哑铃健身软件2015 编辑:程序博客网 时间:2024/06/05 16:42

给定一个数组,取出这个数组中的最大数:

C语言实现:

   1: #include <stdio.h>
   2:  
   3: int getMaxNum(int a[],int length)
   4: {
   5:     int max = 0 ;
   6:     if(length <= 0)
   7:     {
   8:         return max ;
   9:     }
  10:     for(int i = 0 ; i < length ; i++)
  11:     {
  12:         if (max < a[i])
  13:         {
  14:             max = a[i] ;
  15:         }
  16:     }
  17:     return max;
  18:     
  19: }
  20:  
  21: int main()
  22: {
  23:     int array[] = {1,2,3,2,5,9,4,11,32,22,10,2};
  24:     int length = 12 ;
  25:     printf("Max num is:%d",getMaxNum(array,length)) ;
  26:     getchar() ;
  27: }

Java实现:

   1: public class main {
   2:  
   3:     public static void main(String[] args) {
   4:         // TODO Auto-generated method stub
   5:         int []array = new int[]{1,6,8,2,4,5,9,11,3} ;
   6:         System.out.println("最大数:" + getMaxNum(array)) ;
   7:     }
   8:     public static int getMaxNum(int[] array){
   9:         int max = 0 ;
  10:         if(array.length == 0)
  11:         {
  12:             return max ;
  13:         }
  14:         for(int i = 0 ; i < array.length ;i++)
  15:         {
  16:             if(max <= array[i])
  17:             {
  18:                 max = array[i] ;
  19:             }
  20:         }
  21:         return max ;
  22:     }
  23: }
0 0
原创粉丝点击