package com.mjm.exercise;
import java.util.Deque;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public class Sort {
//在一个有序数组中进行 插入
//
public static void insertSort(int arr[]){
int k;
int temp = 0;
int m = 0;
for(int i = 1; i<arr.length;++i){
//寻找插入位置
for(k=0;k<i;k++){
if(arr[k]>arr[i]){
m = i;
break;
}
}
temp = arr[i];
//移位
while(m>k){
arr[m] = arr[m-1];
--m;
}
arr[k] = temp;
}
}
//冒泡排序
public static void bubbleSort(int[] arr){
for(int i = 1;i< arr.length;i++){//控制循环次数n-1次
for(int j = 0;j< arr.length-i;j++){//每次将最大的数放在末尾
if(arr[j]>arr[j+1]){
int temp= arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
//选择排序
public static void selectSort(int[] arr){
int index;
for(int i = 0;i<arr.length-1;i++){
index = i;
for(int j = i+1;j<arr.length;j++){
if(arr[j]<arr[index])
index = j;
}
if(index != i){
int temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
}
}
//快速排序
public static int partQuickSort(int[] arr,int low, int high){
int temp = arr[low];
while(low < high){
while(low<high &&arr[high]>temp)
high--;
if(low<high)
arr[low++] = arr[high];
while(low<high && arr[low]<temp)
low++;
if(low<high)
arr[high--] = arr[low];
}
arr[low] = temp;
return low;
}
public static void quickSort(int[] arr,int low,int high){
if(low<high){
int mid = partQuickSort(arr,low,high);
if(low<mid)
quickSort(arr, low, mid);
if(mid+1<high)
quickSort(arr, mid+1, high);
}
}
public static void heapSort(int[] arr){
int len = arr.length;
while(len>0){
int i = len/2;
while(i>0){
if(arr[i-1]<arr[2*i-1]){
int temp = arr[i-1];
arr[i-1] = arr[2*i-1];
arr[2*i-1] = temp;
}
if(2*i+1<=len && arr[i-1]<arr[2*i]){
int temp = arr[i-1];
arr[i-1] = arr[2*i];
arr[2*i] = temp;
}
i--;
}
int temp = arr[0];
arr[0] = arr[len-1];
arr[(len--)-1] = temp;
}
}
//归并排序 (利用插入排序)
public static void mergeOne(int[] arr,int low,int mid,int high){
for(int i=mid+1;i<=high;i++ ){
for(int j = i;j>low;j--){
if(arr[j] < arr[j-1]){
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
else
break;
}
}
}
//归并排序 1 递归方法
public static void mergeSort(int[] arr,int low,int high){
int mid = (low+high)/2;
if(low<high){
mergeSort(arr,low,mid); //排序左半边
mergeSort(arr,mid+1,high); //排序右半边
mergeOne(arr, low, mid, high);//归并结果
}
}
//归并排序 2 非递归方法
//利用队列
public static void mergeSort(int[] arr){
Queue<Integer> queue = new LinkedBlockingQueue<Integer>();
for(int i = 0;i<arr.length;i++){
queue.offer(i);
queue.offer(i);
}
while(queue.size()>2){
int low = queue.poll();
int mid = queue.poll();
queue.offer(low);
if(mid+1==queue.peek()){
queue.poll();
int high = queue.poll();
queue.offer(high);
mergeOne(arr,low,mid,high);
}else{
queue.offer(mid);
}
}
}
}
JAVA排序算法
最新推荐文章于 2024-08-18 21:36:31 发布