Code Interview Guide for Programmers Chapter 8 Array and Matrix Questions Sorting Arrays of Natural Numbers

topic

自然数数组的排序

java code

package com.lizhouwei.chapter8;

/**
 * @Description: 自然数数组的排序
 * @Author: lizhouwei
 * @CreateDate: 2018/5/8 20:51
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter8_14 {

    public void sort(int[] arr) {
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            if (arr[left] != left + 1) {
                swap(arr, left, arr[left] - 1);
            } else {
                left++;
            }
        }
    }

    public void swap(int[] arr, int a, int b) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }

    //测试
    public static void main(String[] args) {
        Chapter8_14 chapter = new Chapter8_14();
        int[] arr = {2, 3, 6, 5, 4, 1};
        System.out.println("自然数数组 arr = {2, 3, 6, 5, 4, 1}排序后为:");
        chapter.sort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325893242&siteId=291194637