桶排序是将数组分到有限数量的桶子里,每个桶子在个别排序,桶排序时间复杂度为O(n),空间复杂度O(n),不是基于比较的排序。
代码示例数值为0-200value之间的数值排序
public static void bucketSocket(int[] arr){
if(arr==null||arr.length<2){
return;
}
int max=Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++){
max=Math.max(max,arr[i]);}
int[] bucket=new int[max+1];
for(int i=0;i<arr.length;i++){
bucket[arr[i]]++; }
int i=0;
for(int j=0;j<bucket.length;j++){
while(bucket[j]-->0){
arr[i++]=j; }
}}
数组实现栈及数组实现队列代码实现:
publicclass Code_Array_To_Stack_queue {
public static class ArrayStack {
private Integer[] arr;
private Integer size;
public ArrayStack(int initSize){
if (initSize < 0) {
throw newIllegalArgumentException("The init size is less than 0");
}
arr = new Integer[initSize];
size = 0;
}
public Integer peek() {
if (size == 0) {
return null;
}
return arr[size - 1];
}
public void push(int obj) {
if (size == arr.length) {
throw newArrayIndexOutOfBoundsException("The queue is full");
}
arr[size++] = obj;
}
public Integer pop() {
if (size == 0) {
throw newArrayIndexOutOfBoundsException("The queue is empty");
}
return arr[--size];
}
}
public static class ArrayQueue {
private Integer[] arr;
private Integer size;
private Integer first;
private Integer last;
public ArrayQueue(int initSize){
if (initSize < 0) {
throw newIllegalArgumentException("The init size is less than 0");
}
arr = newInteger[initSize];
size = 0;
first = 0;
last = 0;
}
public Integer peek() {
if (size == 0) {
return null;
}
return arr[first];
}
public void push(int obj) {
if (size == arr.length) {
throw newArrayIndexOutOfBoundsException("The queue is full");
}
size++;
arr[last] = obj;
last = last == arr.length- 1 ? 0 : last + 1;
}
public Integer poll() {
if (size == 0) {
throw newArrayIndexOutOfBoundsException("The queue is empty");
}
size--;
int temp = first;
first = first ==arr.length - 1 ? 0 : first + 1;
return arr[temp];
}
public static void main(String[] args) {
}
}
}
系统排序:Arrays.sort(arr)综合排序中当元素较少时用插入排序,小Int、小char、小double等用quick,反之用merge稳定性好。