冒泡排序
public class PaixuMaoPao
{
public static void main(String[] args)
{
int[] arr=[24,69,80,57,13];
Maopao(arr);
System.out.println(arr);
}
private static int Maopao(int[] arr){
for(int j=0;i<=arr.length-1;j++){
for(int i=0;j<=arr.length-1-j;i++){
if(arr[i]>arr[i+1]){
int t=arr[i];
arr[i+1]=t;
arr[i]=arr[i+1];
}
}
}
return arr;
}
}
选择排序
import java.util.Arrays;
public class PaixuXuanZe
{
public static void main(String[] args)
{
int[] arr={1,4,23,2,45,5};
int temp=0;
for(int i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]<arr[j]){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
堆排序
import java.util.Arrays;
public class Dui
{
public static void main(String[] args)
{
int[] arr={1,0,6,7,2,3,4};
int start=(arr.length-1)/2;
for(int i=start;i>=0;i--){
toMaxHeap(arr,arr.length,i);
}
for(int i=arr.length-1;i>0;i--){
int t=arr[0];
arr[0]=arr[i];
arr[i]=t;
toMaxHeap(arr,i,0);
}
System.out.println(Arrays.toString(arr));
}
private static void toMaxHeap(int[] arr,int size,int index){
int leftnode=index*2+1;
int rightnode=index*2+2;
int maxindex=index;
if(leftnode<size && arr[leftnode]>arr[maxindex]){
maxindex=leftnode;
}
if(rightnode<size && arr[rightnode]>arr[maxindex]){
maxindex=rightnode;
}
//来调换位置
if(maxindex!=index){
int temp=arr[maxindex];
arr[maxindex]=arr[index];
arr[index]=temp;
toMaxHeap(arr,size,maxindex);
}
//调换之后影响下面的子树不是大顶堆
}
}
归并排序
import java.util.Arrays;
public class PaixuGuibin
{
public static void main(String[] args)
{
int[] arr={4,5,6,7,1,2,3,4};
chaifen(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
private static void chaifen(int[]arr,int startindex,int endindex){
int centerindex=(endindex+startindex)/2;
if(startindex<endindex){
chaifen(arr,startindex,centerindex);
chaifen(arr,centerindex+1,endindex);
guibin(arr,0,centerindex,arr.length-1);
}
}
private static void guibin(int[] arr,int startindex,int centerindex,int endindex){
int[] tmp=new int[endindex-startindex+1];
int index = 0;
int j = startindex,k = centerindex+1; //左边序列和右边序列起始索引
while(j <= centerindex && k <= endindex){
if(arr[j] < arr[k]){
tmp[index] = arr[j];
index++;
j++;
}else{
tmp[index] = arr[k];
index++;
k++;
}
}
//若左边序列还有剩余,则将其全部拷贝进tmp[]中
while(j <= centerindex){
tmp[index] = arr[j];
index++;
j++;
}
while(k <= endindex){
tmp[index] = arr[k];
index++;
k++;
}
for(int t=0;t<index;t++){
arr[startindex+t] = tmp[t];
}
}
}