java实现计数排序算法

前面我们详细讲解了计数排序算法,今天我们用代码来实现

package ttt;

public class CountingSort {
    public static int[] countingSort(int[] theArray) {
    	int[] lastArray = new int[theArray.length];
        for(int i = 0; i < theArray.length; i++) {
        	int count = 0;
        	for(int j = 0; j < theArray.length; j++) {
        		if(theArray[i] > theArray[j]) {
        			count++;
        		}
        	}
        	lastArray[count] = theArray[i];
        }
    	return lastArray;
    }
    public static void main(String[] args) {
    	int []theArray = {6, 4, 5, 1, 8, 7, 2, 3};
        System.out.print("之前的排序:");
        for(int i = 0; i < theArray.length; i++) {
            System.out.print(theArray[i] + " ");
        }
        
        int []resultArray = countingSort(theArray);
        
        System.out.print("计数排序:");
        for(int i = 0; i < resultArray.length; i++) {
            System.out.print(resultArray[i] + " ");
        }
    }
}

运行结果如下

之前的排序:6 4 5 1 8 7 2 3 计数排序:1 2 3 4 5 6 7 8 

符合预期

你可能感兴趣的:(算法与数据结构)