public class Select {
public static void swap(int[] array,int a,int b){
int temp=array[a];
array[a]=array[b];
array[b]=temp;
}
//选择排序(从剩余元素中选择最小值依次放在0,1,2...位置)
public static void choseselect(int []array){
int minindex;
for(int i=0;i<array.length;i++){
minindex=i;
for(int j=i;j<array.length;j++){
if(array[minindex]>=array[j])minindex=j;
}
swap(array,minindex,i);
}
}
//插入排序(从前往后依次插入到指定位置)
public static void charupaixu(int []array){
for(int i=1;i<array.length;i++){
if(array[i]>=array[i-1])continue;
else {
int j = i;
int temp = array[j];
while (temp < array[j - 1]) {
array[j] = array[j - 1];
j--;
}
array[j] = temp;
}
}
}
//堆排序
//调整节点(数组,要调整的位置,数组长度)
//(important!!!)总结一句,堆排序在调整堆的时候,选择的是左右子树中较大或较小的节点。
public static void adjustindex(int []array,int pos,int len){
//确定子节点
int left_child=pos*2+1;
int right_child=left_child+1;
//判断如果右节点存在并且右节点小于左子节点,选择右子节点,否则选择左子节点
if(right_child<len&&array[right_child]<array[left_child]){left_child=right_child;}
//比较当前节点和最小值节点
if(left_child<len&&array[pos]>array[left_child]){
int temp=array[pos];
array[pos]=array[left_child];
array[left_child]=temp;
adjustindex(array,left_child,len);
}
}
public static void heapSort(int []array){
//构建堆
int i;
int len=array.length;
//从len/2-1开始,因为后续的节点没有子节点。
for (i=len/2-1;i>=0;i--){
//依次向上调整
adjustindex(array,i,len);
}
//将最后一个节点和第一个节点进行交换
for(i=len-1;i>=0;i--){
int temp=array[0];
array[0]=array[i];
array[i]=temp;
//然后调整头节点和当前节点
adjustindex(array,0,i);
}
}
//快速排序
public void Quicksort(int[] alist,int start,int end){
if (start>end)return;
int low=start;
int high=end;
int key=alist[low];
while(low<high){
while(low<high&&alist[high]>=key){
high--;
}
alist[low]=alist[high];
while(low<high&&alist[low]<key){
low++;
}
alist[high]=alist[low];
alist[low]=key;
}
Quicksort(alist,start,low-1);
Quicksort(alist,low+1,end);
}
public static void main(String[] args) {
int array[]={1,7,8,90,2,3,17,15};
//choseselect(array);
//charupaixu(array);
//quicksort(array,0,array.length-1);
heapSort(array);
for(int i=0;i<array.length;i++){
System.out.println(array[i]);
}
}
}
java排序
于 2021-12-24 11:05:22 首次发布