堆排序
package com.sort;
public class HeapSort{
public int[] sort(int[] data, int begin, int end) {
// TODO Auto-generated method stub
BuildMaxHeap(data);
int size = data.length;
while(size>1){
swap(data,0,size-1);
MaxHeap(data, 0, --size);
}
return data;
}
private void BuildMaxHeap(int[] data){
for(int i=data.length/2-1;i>-1;i--){
MaxHeap(data, i,data.length);
}
}
private void MaxHeap(int[] data,int root,int size){
int left = left(root);
int right = right(root);
int large = root;
if(left<=size-1&&data[left]>data[root]){
large = left;
}
if(right<=size-1&&data[right]>data[large]){
large = right;
}
if(large!=root){
swap(data,root,large);
MaxHeap(data,large,size);
}
}
private void swap(int[] data,int m1,int m2){
int tmp = data[m1];
data[m1] = data[m2];
data[m2] = tmp;
}
private int left(int parent){
int left = 2*parent+1;
return left;
}
private int right(int parent){
int right = 2*(parent+1);
return right;
}
}
归并排序
package com.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class MergeSort{
public int[] sort(int[] data, int begin, int end) {
// TODO Auto-generated method stub
if(begin<end){
sort(data,begin,(begin+end)/2);
sort(data,(begin+end)/2+1,end);
merge(data,begin,end,(begin+end)/2);
}
return data;
}
private void merge(int[] data, int begin, int end, int middle) {
// TODO Auto-generated method stub
int[] tmp = new int[end-begin+1];
int i = begin;
int j = middle+1;
int k = 0;
while(i<=middle&&j<=end){
if(data[i]<data[j]){
tmp[k++] = data[i++];
}else{
tmp[k++] = data[j++];
}
}
// 把左边边剩余的数移入数组
while (i <= middle) {
tmp[k++] = data[i++];
}
// 把右边边剩余的数移入数组
while (j <= end) {
tmp[k++] = data[j++];
}
for(int n=0;n<k;n++){
data[begin+n] = tmp[n];
}
}
}
快速排序
package com.sort;
public class QuickSort{
public int[] sort(int[] data, int begin, int end) {
// TODO Auto-generated method stub
if(begin<end){
int i = Partition(data,begin,end);
sort(data,begin,i-1);
sort(data,i,end);
}
return data;
}
private int Partition(int[] data,int begin,int end){
int base = data[end];
int i = begin;
for(int j=begin;j<end;j++){
if(data[j]<base){
swap(data,i,j);
i++;
}
}
swap(data,i,end);
return i;
}
private void swap(int[] data,int m1,int m2){
int tmp = data[m1];
data[m1] = data[m2];
data[m2] = tmp;
}
}
其他算法补充中。。