Java常用排序算法

選擇排序法

/**
*	@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 stub
		int[] 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));
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章