いくつかの一般的なソートアルゴリズムjava実装

2653 ワード

public class sort {
	public static void main(String[] args) {
		int[] a= {10,1,35,14,9,12,11};
		int c=(int)Math.floor(Math.random()*7);
		switch(c){
			case 1:
				BubbleSort(a);
				break;
			case 2:
				SelectSort(a);
				break;
			case 3:
				InsertSort(a);
				break;
			case 4:
				HeapSort(a);
				break;
			case 5:
				MergeSort(a,0,1);
				break;
			case 6:
				QuickSort(a,0,a.length);
				break;
			default:
				break;
		}
		System.out.println(c);
		System.out.println(Arrays.toString(a));
	}
	//    
	public static void BubbleSort(int[] a) {
		for(int i = 0;i 0; j--) {
				if (a[j] < a[j - 1]) {					
					int temp = a[j];
					a[j] = a[j - 1];
					a[j - 1] = temp;
				}
				else {
					break;
				}
			}
		}
	}
	//   
	public static void HeapSort(int[] a) {
	
	}
	//    
	public static void MergeSort(int[] a, int s, int len) {
		int size = a.length;
        int mid = size / (len << 1);
        int c = size & ((len << 1) - 1);
        // -------                  -------//
        if (mid == 0)
            return;
        // ------        -------//
        for (int i = 0; i < mid; ++i) {
            s = i * 2 * len;
            merge(a, s, s + len, (len << 1) + s - 1);
        }
        // -------                -------//
        if (c != 0)
            merge(a, size - c - 2 * len, size - c, size - 1);
        // -------           ------//
        MergeSort(a, 0, 2 * len);
	}
	private static void merge(int[] a, int s, int m, int t) {
        int[] tmp = new int[t - s + 1];
        int i = s, j = m, k = 0;
        while (i < m && j <= t) {
            if (a[i] <= a[j]) {
                tmp[k] = a[i];
                k++;
                i++;
            } else {
                tmp[k] = a[j];
                j++;
                k++;
            }
        }
        while (i < m) {
            tmp[k] = a[i];
            i++;
            k++;
        }
        while (j <= t) {
            tmp[k] = a[j];
            j++;
            k++;
        }
        System.arraycopy(tmp, 0, a, s, tmp.length);
    }
	//    
	public static void QuickSort(int a[],int low,int high) {
		int l=low;
		int h=high;
		int povit=a[low];
		 
		while(l=povit)
			h--;
			if(llow)QuickSort(a,low,l-1);
		if(h
      。    int a[],    Int[] a,         ?