您的位置:首页 > 其它

输入整型数组和排序标识,对其元素按照升序或降序进行排序

2017-01-10 00:00 471 查看

题目描述

输入整型数组和排序标识,对其元素按照升序或降序进行排序


输入描述

1、输入需要输入的整型数个数


输出描述

输出排好序的数字


输入例子

8
1 2 4 9 3 55 64 25
0


输出例子

1 2 3 4 9 25 55 64


算法实现

import java.util.Arrays;
import java.util.Scanner;

/**
* Declaration: All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
while (scanner.hasNext()) {
int n = scanner.nextInt();
int[] array = new int
;
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
int tag = scanner.nextInt();
System.out.println(arrToStr(sort(array), tag));
}

scanner.close();
}

private static String arrToStr(int[] a, int tag) {

StringBuilder builder = new StringBuilder();

if (tag == 1) {
for (int i = a.length - 1; i >= 0; i--) {
builder.append(a[i]).append(' ');
}
} else {
for (int i : a) {
builder.append(i).append(' ');
}
}

return builder.substring(0, builder.length() - 1);
}

private static int[] sort(int[] a) {

for (int i = 0; i < a.length; i++) {
int idx = i;
int tmp;
for (int j = i + 1; j < a.length; j++) {
if (a[idx] - a[j] > 0) {
idx = j;
}
}

tmp = a[i];
a[i] = a[idx];
a[idx] = tmp;
}

return a;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐