Java常用排序算法

来源:互联网 发布:c语言中合法的关键字 编辑:程序博客网 时间:2024/06/07 19:56

选择排序法

/***@Method 选择排序法**/private int[] array = new int[10];protected void selected_sort(){int index;for(int i=0; i < array.length; i++){index = 0;for(int j=0; j < array.length - i; j++){if(array[j] > array[index]){index = j;}}//交换在位置 array.length-i 和 index (最大值) 上的两个数int temp = array[array.length-i];array[array.length-i] = array[index];array[index] = temp;}}

冒泡排序法

/***@Method 冒泡排序法**/private int[] array = new int[10];protected void Bubble_sort(){int index;for(int i=0; i < array.length; i++){//比较两个相邻的数,较大的往后冒泡for(int j=0; j < array.length - i; j++){if(array[j] > array[j + 1]){int temp = array[j];array[j] = array[j + 1];array[j + 1] = temp;}}}}

快速排序法

public static int partition(int []array,int lo,int hi){        //固定的切分方式        int key=array[lo];        while(lo<hi){            while(array[hi]>=key&&hi>lo){//从后半部分向前扫描                hi--;            }            array[lo]=array[hi];            while(array[lo]<=key&&hi>lo){从前半部分向后扫描                lo++;            }            array[hi]=array[lo];        }        array[hi]=key;        return hi;    }        public static void sort(int[] array,int lo ,int hi){        if(lo>=hi){            return ;        }        int index=partition(array,lo,hi);        sort(array,lo,index-1);        sort(array,index+1,hi);     }

归并排序

package check;import java.util.Arrays;/** * 归并排序 * 平均O(nlogn),最好O(nlogn),最坏O(nlogn);空间复杂度O(n);稳定;较复杂 * @author 97650 * */public class MergeSort {public static int[] sort(int[] nums, int low, int high) {int mid = (low + high) / 2;if(low < high) {//左边sort(nums, low, mid);//右边sort(nums, mid + 1, high);//左右归并merge(nums, low, mid, high);}return nums;}private static void merge(int[] nums, int low, int mid, int high) {// TODO Auto-generated method stubint[] temp = new int[high - low + 1];int i = low;//做指针int j = mid + 1;int k = 0;//把较小的数先移到新数组中while (i <= mid && j <= high) {if (nums[i] < nums[j]) {temp[k++] = nums[i++];} else {temp[k++] = nums[j++];}}//把左边的剩余的数移入数组while (i <= mid) {temp[k++] = nums[i++];}//把右边剩余的数移入数组while (j <= high) {temp[k++] = nums[j++];}//把新数组中的数覆盖nums数组for (int k2 = 0; k2 < temp.length; k2++) {nums[k2 + low] = temp[k2];}}public static void main(String[] args) {int[] nums = {2, 7, 8, 3, 1, 6, 9, 0, 5, 4};MergeSort.sort(nums, 0, nums.length - 1);System.out.println(Arrays.toString(nums));}}


原创粉丝点击