1. 程式人生 > >第二天學習筆記之簡單排序(氣泡排序、選擇排序、插入排序)

第二天學習筆記之簡單排序(氣泡排序、選擇排序、插入排序)

public class demo {
    public static void main(String[] args) {
        //陣列長度 方便整合測試
        int length = 10000;
        //生成隨機數long測試 邊界1--1000
        long min = 1;
        long max = 1000000;

        BatSort batSort = new BatSort(length);
        for (int i = 0; i < length; i++) {
            batSort.insert(min 
+ (long) (new Random().nextDouble() * (max - min))); } batSort.display(); long start,end; start = System.currentTimeMillis(); //batSort.bubbleSort(); batSort.selectSort(); //batSort.insertSort(); end = System.currentTimeMillis(); System.out.println(
"Run Time:" + (end - start) + "(ms)"); batSort.display(); } }
public class BatSort {
    private long[] arr ;
    private int elements = 0;

    public BatSort(int arraylength){
        if (arraylength > 0){
            arr = new long[arraylength];
        }else{
            arr = new
long[100]; } } public void insert(long value){ arr[elements] = value; elements++; } /*氣泡排序思想 把最小的資料依次冒泡最前面 舉例 5 2 4 1 3 * 第一次排序 1和3做比較不變 * 第二次排序 4和1做比較 變成 5 2 1 4 3 * 第三次排序 2和1做比較 變成 5 1 2 4 3 * 第四次排序 5和1做比較 變成 1 5 2 4 * 範圍迴圈排序依次類推 */ public void bubbleSort(){ long temp = 0; for (int i=0;i<elements;i++){ for(int j=arr.length -1;j>i;j--){ if(arr[j] < arr[j-1]){ temp=arr[j-1]; arr[j-1]=arr[j]; arr[j]=temp; } } } } /*選擇排序思想 每次排序把最小的元素放在最前面即和待排序的位置對調 舉例 5 2 4 1 3 * 第一次排序 1 2 4 5 3 5和1調換位置 * 第二次排序 1 2 4 5 3 * 第三次排序 1 2 3 5 4 * 第四次排序 1 2 3 4 5 */ public void selectSort(){ long temp = 0; long min = 0; int index = 0; for(int i=0;i<elements;i++){ min = arr[i]; for(int j=elements-1;j>i;j--){ if(min > arr[j]){ min = arr[j]; index = j; } } if(arr[i] > min){ temp = arr[i]; arr[i] = min; arr[index] = temp; } } } /*插入排序思想 取其中一位作為分割位,跟左邊的值比較,如果大於就停止 舉例 5 4 3 2 1 * 第一次排序 4 5 3 2 1 2和5調換位置 * 第二次排序 4 3 5 2 1 4和5調換位置 * 3 4 5 2 1 3和4調換位置 * 第三次排序 3 4 2 5 1 5和2調換位置 * 依次類推 */ public void insertSort(){ long temp = 0; int index = 0; for(int i=1;i<elements;i++){ temp = arr[i]; index = i - 1; while (index>=0&&arr[index] > temp){ arr[index+1] = arr[index]; index--; } arr[index+1] = temp; } } public void display(){ for(int i=0;i<elements;i++){ System.out.print(arr[i] + " "); } System.out.println(); } }