算法與數據結構之簡單排序

簡單排序:

1.冒泡排序

2.選擇排序

3.插入排序

代碼:SimpleSort.java

package com.caicongyang.sort;

/**
 * 
 * 
 * @author caicongyang1
 * @version $Id: SimpleSort.java, v 0.1 2016年5月31日 下午4:15:07 caicongyang1 Exp $
 */
public class SimpleSort {
    public static void main(String[] args) {
        int[] arr = { 10, 4, 5, 7, 2, 3, 8 };
        System.out.println(arr[arr.length - 1]);
        //bubbleSort(arr);
        //selectionSort(arr);
        insertionSort(arr);
        for (int i : arr) {
            System.out.println(i);
        }

    }

    /**
     *插入排序
     *將數組分成有序部分和無序部分,將無序的依次插入有序部分中
     * 
     * @param arr
     */
    public static void insertionSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {//外層總1開始,
            int temp = arr[i];
            int j = i;
            while (j > 0 && arr[j - 1] >= temp) {//內層從外層開始,向左移動,直到他不能向左移動位置(排到到應有的位置)
                arr[j] = arr[j - 1]; //向左移動 
                --j;

            }
            arr[j] = temp; //插入對應的位置
        }
    }

    /**
     * 選擇排序
     * 
     * 將最小的放在未排序的最前面,依次交換
     * 
     * 
     */
    public static void selectionSort(int[] arr) {
        int min; //定義最小的變量
        for (int i = 0; i < arr.length - 1; i++) { //外層從數組最小的位置0開始,到數組的倒數第二個位置
            min = i; //默認最小爲數組第一個
            for (int j = i + 1; j < arr.length; j++) { //內層從i+1開始,到數組的最後一個位置,依次比較,如果當前數比min更小,則將內層的數換到min位置
                if (arr[j] < arr[min]) {
                    min = j;
                }
                int temp = arr[i];
                arr[i] = arr[min];
                arr[min] = temp;
            }

        }
    }

    /**
     * 冒泡排序
     * 
     * 逐個交換,將最大的放到最後一個,依次類推
     *
     */
    public static void bubbleSort(int[] arr) {
        for (int i = arr.length - 1; i > 1; i--) { //外層從數組的最後一個位置開始,依次遞減,後面的位置是排序好的
            for (int j = 0; j < i; j++) {//內層從0開始,逐個比較,直到內層等於外層的時候結束,將最大的一個換到最後的位置
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j]; //交換對換位置
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

更多精彩內容請繼續關注我的博客http://blog.csdn.net/caicongyang

記錄與分享,你我共成長 -from caicongyang

如果你覺得本文對你有幫助,可以掃描下面的微信二維碼,請我喝杯水咯!



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