zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第八章 数组和矩阵问题 自然数数组的排序

    题目

    自然数数组的排序
    

    java代码

    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] + " ");
            }
        }
    }
    
    

    结果

  • 相关阅读:
    Kafka 高级API 实战
    CDH 5.16.1 离线安装 Spark 2.3
    CDH5.16.1 离线安装 Kafka
    CDH5.16.1新增节点
    mysql搭建主从结构
    Kerberos常见错误
    expect实现脚本的 自动交互
    寒假day27
    寒假day26
    寒假day25
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/9010980.html
Copyright © 2011-2022 走看看