Java算法之排序的另一种实现

来源:互联网 发布:无锡安镇网络 编辑:程序博客网 时间:2024/05/16 08:48


package com.test;

public class OtherSort {

 /*
  * 当我们知道一个数组里所有值得范围的时候,我们可以用另外一种方法实现排序功能。
  * 借助一个辅助空间,该辅助空间的大小就是这个数组中最大值得大小。
  * 辅助空间(数组)的下标就是要被排序数组里的值,辅助空间(数组)每个位置的值就是被排序数组里的值出现的次数。
  * 这样就可以在O(n)时间内对一个比较大的数组进行排序。
  * 前提是该数组里的值有一定的范围,比如说公司员工的年龄(肯定不会大于99岁)等
  */
 
 public void AnotherSortMethod(int ages[],int length){
  
  try{
   
   //判断输入的年龄数组是否为空,以及大小是否为0
   if(ages == null || length < 0){
    
    throw new Exception("Invalid Input!");
   }
   
   int oldestAge = 99;
   int timesOfAge[];
   timesOfAge = new int[oldestAge + 1];
   
   //初始化timesOfAge数组
   for(int i = 0;i<oldestAge;i++){
    timesOfAge[i]=0;
   }
   
   //统计每个年龄在数组ages中出现的次数,然后以年龄为下标把该年龄出现的次数存储到timesOfAge数组中。
   for(int i = 0;i < length;i++){
    int age = ages[i];
    if(age < 0 || age > oldestAge){
     throw new Exception("age out of Range!");
    }
    ++timesOfAge[age];
   }
   
   //把timesOfAge中排好序的值存储到ages数组中
   int index = 0;
   for(int i = 0;i<oldestAge;i++){
    for(int j=0;j<timesOfAge[i];j++){
     ages[index]=i;
     index++;
    }
   }
   
  }catch(Exception e){
   e.printStackTrace();
  }

 }
}

0 0
原创粉丝点击