2020-absolute value sorting (java)

Insert picture description here
Idea : The idea of ​​this question is relatively clear, input data, use the math method to compare the size and value, and traverse the output.

import java.util.*;
public class Main {
    
    
public static void Main(String[] args) {
    
    
	Scanner a=new Scanner(System.in);
	while(a.hasNext())
	{
    
    
		int n=a.nextInt();
		if(n==0)
			break;
		int[] arr=new int[n];
		for(int i=0;i<arr.length;i++) //向数组中录入数据
		{
    
    
			arr[i]=a.nextInt();
		}
		for(int j=0;j<arr.length;j++) //比较绝对值大小并排序
		{
    
    
			int sort=0;
			for(int y=j;y<arr.length;y++)
			{
    
    
				if(Math.abs(arr[j])<Math.abs(arr[y]))
					{
    
    
						sort=arr[j];
						arr[j]=arr[y];
						arr[y]=sort;
					}
			}
		}
		for(int k=0;k<arr.length;k++)  //遍历输出
		{
    
    
			if(k==0)
				System.out.print(arr[k]);
			else
				System.out.print(" "+arr[k]);
		}
		System.out.println();
	}
}
}

I write a lot, I think it can be simplified, let go first.
If there are errors, please correct me

Guess you like

Origin blog.csdn.net/weixin_45956604/article/details/113757436