选择排序

选择排序法:选择排序和堆排序

选择排序(数组实现)

public void select_sort(){
int position;
for(position = entry.length-1;position >=0;position--){
int max = max_in_the_list(0,position);
swap(position,max);
}
}
public void swap(int first,int second){
int temp =entry[first];
entry[first]=entry[second];
entry[second] = temp;
}
public int max_in_the_list(int low,int high){
int largest;
largest = low;
for(int i = low+1;i<=high;i++)
if(entry[i] > entry[largest])
largest = i;
return largest;
}

堆排序(数组实现)

public void heap_sort(){
int current;
int last_unsorted;
build_heap();
for(last_unsorted = count -1;last_unsorted >0;last_unsorted--){
current = entry[last_unsorted];
entry[last_unsorted]= entry[0];
insert_heap(current,0,last_unsorted-1);
}
}
private void insert_heap(int current, int low, int high) {
int large;
large = 2*low +1;
while(large<=high){
if(large<high && entry[large]<entry[large+1]){
large++;
}
if(current>=entry[large])
break;
else{
entry[low]=entry[large];
low = large;
large = 2*low +1;
}
}
entry[low]=current;
}
private void build_heap() {
int low;
for(low=count/2-1;low>=0;low--){
int current = entry[low];
insert_heap(current,low,count-1);
}
}



选择排序(表实现)

堆排序(表实现)

posted @ 2012-01-18 15:34  ymin  阅读(201)  评论(0编辑  收藏  举报