數組排序,js數組排序

來源:互聯網
上載者:User

數組排序,js數組排序
一 概述1.雙層迴圈

排序通常由雙層迴圈實現,外層迴圈控制迴圈輪數,內層迴圈實現單次排序。外層迴圈的索引從1到arr.length-1,內層迴圈迴圈次數隨外層迴圈迴圈次數的增加而減少。

二 冒泡法1.基本思想

對比相鄰的兩個元素,如果滿足條件,則交換位置,這樣就把較大的元素移動到後面了。

2.演算法實現
public static int[] bubbleSort(int[] arr) {        for (int i = 1; i < arr.length; i++) {            for (int j = 0; j < arr.length - i; j++) {                if (arr[j] > arr[j + 1]) {                    int temp = arr[j];                    arr[j] = arr[j + 1];                    arr[j + 1] = temp;                }            }        }        return arr;    }
三 直接排序1.基本思想

從未排序序列中篩選出最大值,放在未排序序列的尾部。外層迴圈迴圈一次,交換未排序序列最大值與未排序序列最後一個元素的位置,其他元素位置不變,關鍵是擷取最大值的索引。直接排序比冒泡排序快。

內層迴圈切入點:假定未排序序列第一個即索引為0的元素為最大值,然後將其與剩餘元素進行對比,擷取最大值的索引。

2.演算法實現
public static int[] directSort(int[] arr) {        int len = arr.length;        int index;        for (int i = 1; i < len; i++) {            index = 0;            for (int j = 1; j <= len - i; j++) {                if (arr[index] < arr[j]) {                    index = j;                }                int temp = arr[len - i];                arr[len - i] = arr[index];                arr[index] = temp;            }        }        return arr;    }
四 反轉排序1.基本思想

交換索引和為arr.length-1的兩個元素的位置,只需一層迴圈,迴圈次數為arr.length/2-1。

2.演算法實現
public static int[] reverseSort(int[] arr) {        for (int i = 0; i < arr.length / 2; i++) {            int temp = arr[i];            arr[i] = arr[arr.length - 1 - i];            arr[arr.length - 1 - i] = temp;        }        return arr;    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.