常用的排序算法(一)

    xiaoxiao2025-07-07  6

    public class SortUtil {

    /** * @param args */ public static void main(String[] args) { int [] array = new int[]{4,9,5,2,3,1,7,10,2,88,99,0};

    // MpSort(array); // SSort(array); // QSort(array,0,array.length-1); // InsertSort(array); shellSort(array);

    for(int i = 0; i<array.length;i++){ System.out.println(array[i]); } } public static void ShellSort(int[] a){ } public static void shellSort(int[] a) { int gap = 1, i, j, len = a.length; int temp;//插入排序交换值的暂存 //确定初始步长 while (gap < len / 3){ gap = gap * 3 + 1; } for (; gap > 0; gap /= 3){//循环遍历步长,最后必为1 for (i = gap; i < len; i++) {//每一列依次向前做插入排序 temp = a[i]; //每一列中在a[i]上面且比a[i]大的元素依次向下移动 for (j = i - gap; j >= 0 && a[j] > temp; j -= gap){ a[j + gap] = a[j]; } //a[i]填补空白,完成一列中的依次插入排序 a[j + gap] = temp; } } } public static void InsertSort(int[] a){ for(int i= 1;i<a.length;i++){ int location = 0; int temp = a[i]; boolean need = false; for(int j = i-1;j>=0;j--){ if(temp>a[j]){ a[j+1] = a[j]; location = j; need = true; }else{ break; } } if(need){ a[location] = temp; } for(int p = 0; p<a.length;p++){ System.out.print(a[p]+ " "); } System.out.println(""); } } public static void QSort(int[] a,int start,int end){ if(end > start){ int medille = getMidlle(a,start,end); QSort(a,start,medille-1); QSort(a,medille+1,end); } } public static int getMidlle(int[] a,int start,int end){ int temp = a[start]; while(end > start){ while(end > start && temp >= a[end]){ end --; } a[start] = a[end]; while(end > start && temp <=a [start]){ start ++; } a[end] = a[start]; } a[start] = temp; return start; } public static void SSort(int[] a){ int length = a.length; for(int i = 0;i < length;i++){ int min = i; for(int j=i;j<length;j++){ if(a[min]>a[j]){ min = j; } } if(i != min){ int temp = 0; temp = a[i]; a[i] = a[min]; a[min] = temp; } } } public static void MpSort(int[] array){ int boundtemp = 1; int bound = array.length - 1; while(bound > 0){ for(int i=0 ;i < bound ;i++){ if(array[i] > array[i+1]){ int temp = 0; temp = array[i]; array[i] = array[i+1]; array[i+1] = temp; boundtemp = i; } } bound = boundtemp; } }

    }

    转载请注明原文地址: https://ju.6miu.com/read-1300451.html
    最新回复(0)