import java.util.Arrays;
/**
* Created with Intellij IDEA
* ClassName:Test
* User:MaLe
* Description:
*
* @Date:2021/11/11
* @Time:9:13
* @author:395645313@qq.com
*/
public class Test {
//插入排序
public static void insertSort(int[] arr){
for (int i = 0; i <arr.length; i++) {
int tmp=arr[i];
int j = i-1;
for (; j >=0; j--) {
if (tmp<arr[j]){
arr[j+1]=arr[j];
}else{
break;
}
}
arr[j+1]=tmp;
}
}
//选择排序
public static void selectSort(int[] arr) {
for (int i = 0; i < arr.length ; i++) {
for (int j = i+1; j <arr.length; j++) {
if (arr[i]>arr[j]){
int tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}
}
}
}
//冒泡排序
public static void bubbleSort(int[] arr){
for (int i = 0; i <arr.length-1; i++) {
boolean flg=false;
for (int j = 0; j <arr.length-1-i; j++) {
if (arr[j]>arr[j+1]){
int tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
flg=true;
}
}
if (!flg){
break;
}
}
}
//快速排序
public int partiStion(int[] nums,int start,int end){
int tmp=nums[start];
while(start<end){
while(start<end && tmp<=nums[end]){
end--;
}
nums[start]=nums[end];
while(start<end && tmp>=nums[start]){
start++;
}
nums[end]=nums[start];
}
nums[start]=tmp;
return start;
}
public void quckly(int[] nums,int low,int high){
if(low>=high) return;
int pivot=partiStion(nums,low,high);
quckly(nums,low,pivot-1);
quckly(nums,pivot+1,high);
}
public void sortColors(int[] nums) {
quckly(nums,0,nums.length-1);
}
//堆排序
public static void shiftDown(int[] arr,int parent,int len) {
int child = (2*parent )+1;
while(child<len){
if(child+1<len && arr[child]<arr[child+1]){
child++;
}
if(arr[child]>arr[parent]){
int tmp=arr[child];
arr[child]=arr[parent];
arr[parent]=tmp;
parent=child;
child=2*parent+1;
}else{
break;
}
}
}
public static void createHeap(int[] arr){
for (int i = (arr.length-1-1) ; i >=0 ; i--) {
shiftDown(arr,i,arr.length);
}
}
public static void heapSort(int[] arr){
//大根堆
createHeap(arr);
int end=arr.length-1;
while(end>0){
int tmp=arr[end];
arr[end]=arr[0];
arr[0]=tmp;
shiftDown(arr,0,end);
end--;
}
}
JAVA 排序
最新推荐文章于 2024-09-01 15:30:33 发布