資料結構與演算法---選擇排序_演算法

來源:互聯網
上載者:User
選擇排序 思想:每一次從待排序的資料元素中選出最小的或者最大的,直到全部待排序的元素排序完成。 待排序的元素:int[] arr = {6,5,4,3,2,1}; 運行截圖:
步驟:每一趟我們找出來的最小值使用加粗黑體表示 第幾趟 6 5 4 3 2 1 0 1 5 4 3 2 6 1 1 2 4 3 5 6 2 1 2 3 4 5 6 3 1 2 3 4 5 6 4 1 2 3 4 5 6 5 1 2 3 4 5 6

最後趟就沒有必要存在了因為它前面的已經都是有序了。 代碼如下:

public class XuanZe {    public static void main(String[] args) {        // TODO 自動產生的方法存根        int[] arr = {6,5,4,3,2,1};        xuanZePaiXu(arr);        System.out.println("排序後的結果為:");        for (int i = 0; i < arr.length; i++) {            System.out.print(arr[i]+"\t");        }    }    private static void xuanZePaiXu(int[] arr) {        for (int i = 0; i < arr.length-1; i++) {            int temp = 0;            int index = i;  //用來儲存最小值的索引            for (int j = i+1; j < arr.length; j++) {                if (arr[index] > arr[j]) {                    index = j;                }            }            temp = arr[index];            arr[index] = arr[i];            arr[i] = temp;        }    }}

我們列印出每一趟的排序之後的數組時發現和我們自己寫的是一樣的。

冒泡排序的連結如下:點擊即可查看冒泡排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.