题目
自然数数组的排序
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] + " ");
}
}
}
结果