23 自然数数组对排序
Table of Contents

ac(就地交换)

import java.util.Scanner;


public class Main {

    public static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        int n = sc.nextInt();
//        int n = 1;
        int[] arr = new int[n];
        for(int i = 0; i < n; i ++){
            arr[i] = sc.nextInt();
        }
        int index = 0;
        while (index < n){
            int targetVal = index + 1;
            int curVal = arr[index];
            if(targetVal == curVal){
                index ++;
            }else {
                // swap
                int tmp = arr[curVal - 1];
                arr[curVal - 1] = curVal; //  该元素到位了
                arr[index]= tmp;
            }
        }
        for(int i=0;i<n-1;i++){
            System.out.print(arr[i] + " ");
        }
        System.out.println(arr[n-1]);
    }

}
/*
5
2 1 4 5 3

1 2 3 4 5

eg:

4 1 2 5 3
-> 5 1 2 4 3
-> 3 1 2 4 5
-> 2 1 3 4 5
-> 1 2 3 4 5
*/