Java選擇排序,插入排序,快速排序

來源:互聯網
上載者:User

標籤:插入   string   print   class   logs   需要   bre   main   java   

public class Test {    public static void main(String[] args) {        int a[] = { 1, 2, 3, 4, 5 };        // 選擇排序(a);        // 插入排序(a);        quicksort(a, 0, a.length - 1);        System.out.print("排序後:");        for (int n : a) {            System.out.print(n + " ");        }    }    static void 選擇排序(int[] a) {        int pos = 0;        for (int i = 0; i < a.length - 1; i++) {            pos = i;            // 定位到i之後的最值            for (int j = i; j < a.length; j++) {                if (a[pos] < a[j]) {                    pos = j;                }            }            // 最值和i值交換            int t = a[pos];            a[pos] = a[i];            a[i] = t;        }    }    static void 插入排序(int[] arr) {        for (int i = 1; i < arr.length; i++) {            System.out.print(i + ":");            // 假定(0->(j-1))是有序的,看j排在哪裡            for (int j = i; j > 0; j--) {                if (arr[j] > arr[j - 1]) {                    int temp = arr[j];                    arr[j] = arr[j - 1];                    arr[j - 1] = temp;                } else {                    // 假定前面是有序的,則只需要交換一次即可                    break;                }            }            for (int n : arr) {                System.out.print(n + " ");            }            System.out.println();        }    }    static void quicksort(int arr[], int left, int right) {        if (left < right) {            // 定位最左            int key = arr[left];            int i = left;            int j = right;            while (i < j) {                while (i < j && arr[j] < key) {                    // 高標左移←                    j--;                }                if (arr[i] != arr[j]) {                    // 高位:小的往左邊拉                    arr[i] = arr[j];                }                while (i < j && arr[i] > key) {                    // 低標右移→                    i++;                }                if (arr[i] != arr[j]) {                    // 低位:大的往右邊拉                    arr[j] = arr[i];                }            }            arr[i] = key;            quicksort(arr, left, i - 1);            quicksort(arr, i + 1, right);        }    }}

 

Java選擇排序,插入排序,快速排序

聯繫我們

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