1. 程式人生 > >Java實現對公司所有員工的年齡排序

Java實現對公司所有員工的年齡排序

 

要求:對公司的員工年齡進行排序,員工人數大約萬名左右,可使用常量大小的輔助空間,要求時間效率為O(n)。

實現思路:使用一個額外的輔助陣列用來記錄同齡的員工數目。

實現如下:

 程式碼解讀:

1)

 // 初始化一個odlAge+1的陣列
        int[] timeOfAge = new int[oldAge + 1];
        // 將陣列元素都置為0
        for (int i = 0; i < timeOfAge.length; i++) {
            timeOfAge[i] = 0;
        }

 timeOfAge[]的長度為81,元素全部為0

 

2)age[0]=23,於是timeOfAge[23]=1;  age[1]=45,於是timeOfAge[45]=1;age[ 2]=32,於是timeOfAge[32]=1;

.....age[4]=21,於是timeOfAge[21]=2;以此類推timeOfAge陣列對應年齡的位置設定多少次

   // 某個年齡出現了多少次,就在timeOfAge陣列對應年齡的位置設定多少次
        for (int j = 0; j < ages.length; j++) {
            int a = ages[j];
            timeOfAge[a]++;
        }

3)初始,第一個for{}  中  index=0,i=20,

第二個for{}   ,  j=0, timeOfAge[ 20]=0,所以 j < timeOfAge[i]不成立,執行i++,

於是i=21,timeOfAge[ 21]=2, 執行 ages[index] = i; 得到ages[0]=21,   index++; 

再得到age[1]=21; index++ 

 int index = 0;
        for (int i = youngAge; i <= oldAge; i++) {// 按照年齡從小到大依次遍歷timeOfAge
            for (int j = 0; j < timeOfAge[i]; j++) {// 在timeOfAge中取得各個年齡位置記錄的出現次數
                ages[index] = i;// 將新陣列從頭設定出現的年齡,已經排好序
                index++;
            }
        }
    }

 

import java.util.Arrays;

public class AgeSort {

    public static void main(String[] args) {

        int[] ages = new int[] { 23, 45, 32, 43, 21, 24, 25, 23, 22, 22, 21 };
        System.out.println("原陣列為:" + Arrays.toString(ages));
        AgeSort as = new AgeSort();
        as.sortAge(ages);
        System.out.println("排序後的陣列為:" + Arrays.toString(ages));
    }

    private void sortAge(int[] ages) {

        if (ages == null || ages.length < 1) {
            return;
        }
        int oldAge = 80;
        int youngAge = 20;

        // 初始化一個odlAge+1的陣列
        int[] timeOfAge = new int[oldAge + 1];
        // 將陣列元素都置為0
        for (int i = 0; i < timeOfAge.length; i++) {
            timeOfAge[i] = 0;
        }
        // 某個年齡出現了多少次,就在timeOfAge陣列對應年齡的位置設定多少次
        for (int j = 0; j < ages.length; j++) {
            int a = ages[j];
            timeOfAge[a]++;
        }

        int index = 0;
        for (int i = youngAge; i <= oldAge; i++) {// 按照年齡從小到大依次遍歷timeOfAge
            for (int j = 0; j < timeOfAge[i]; j++) {// 在timeOfAge中取得各個年齡位置記錄的出現次數
                ages[index] = i;// 將新陣列從頭設定出現的年齡,已經排好序
                index++;
            }
        }
    }
}

程式碼也可以寫成:

public static void sort(int []ages){
		int oldestAge=100;
		int []timesOfAges=new int[oldestAge];
		
		int len=ages.length;
		for(int i=0;i<len;i++){
			timesOfAges[ages[i]]++;;
		}
 
		
		//排序
		int index=0;
		for(int i=0;i<oldestAge;i++){
			for(int j=0;j<timesOfAges[i];j++){
				
				ages[index]=i;
				index++;
			}
		}
		
	
	}

參考自:https://blog.csdn.net/a1247529789/article/details/51173993

https://blog.csdn.net/sinat_32393077/article/details/73894895