一種時間複雜度爲O(n)的排序方法

代碼以下:java

import java.util.BitSet;c++

import com.sun.java_cup.internal.internal_error;算法

 

public class Sort編程

{數組

private static boolean[] temp=new boolean[10000];數據結構

/**編程語言

 * @notice 注意參數中的array數組中的每一個元素大小不能超過9999,並且不能有重複元素。spa

 * 同時也就意味着array數組大小不能超過10000,其中元素大小在0-9999的這樣一個範圍。排序

 */it

public void sort(int[] array)

{

init();

for(int i=0;i<array.length;i++)

{

temp[array[i]]=true;

}

int loc=0;

for(int j=0;j<temp.length;j++)

{

if(temp[j])

array[loc++]=j;

}

}

private void init()//其實在此方法中經過傳一個整數能夠剪枝,而整數爲array數組中元素的最大值

{

for(int i=0;i<temp.length;i++)

temp[i]=false;

}

public void print(int[] array)

{

for(int i=0;i<array.length;i++)

System.out.print(array[i]+"  ");

System.out.println();

}

public static void main(String[] args)

{

Sort sort=new Sort();

int array[]=new int[]{3,5,1,2,10,88,25,66};

sort.print(array);

sort.sort(array);

sort.print(array);

}

}

*************運行結果*************

3  5  1  2  10  88  25  66  

1  2  3  5  10  25  66  88 

    

今天在看《編程珠璣》開始的時候,做者提到了位示圖的數據結構,受其啓發想到了這樣一種排序方法,不過這種排序算法對傳入的數組有着嚴格要求,不能重複,並且數組中元素的數值範圍受輔助數組的大小的制約,可是此排序算法相對來講仍是很快的,時間複雜度爲O(n)。感受美中不足的是貌似主流編程語言中沒有提供一種bit的數據類型,否則會大大減少前邊提到的元素數值範圍所受的限制。本人仍是一位剛入職的菜鳥,鑑於所學有限,不足之處望你們能多多指正。
相關文章
相關標籤/搜索