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

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

http://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309

输入

  • 读取元素个数,用于确定数组容量
  • 依次读取数组
  • 读取正/倒序

处理

采用冒泡,子循环用于确认当前值为之后值的最大/小。外循环用于确定所有元素都比较到

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int num = 0;
    if (in.hasNextInt()) {

    num = in.nextInt();
    }
    
    int[] array = new int[num];
    if (in.hasNextLine()) {
      for (int i = 0; i < num && in.hasNextInt(); i++) {
        array[i] = in.nextInt();
      }
    }

    
    int order = 0;
    if (in.hasNextInt()) {
      order = in.nextInt();
    }
//     System.out.println("num:"+num);
//     System.out.println("order:"+order);
    for(int i = 0; i < num - 1; i++) {
      for(int j = i; j <num; j++) {
        if(order == 0) {
          if (array[i] > array[j]) {
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
          }
        } else if (order == 1) {
          if (array[i] < array[j]) {
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
          }
        }
      }
    }
    for(int i = 0; i < num; i++) {
      System.out.print(array[i]);
      if ( i < num -1){
      System.out.print(" ");
      }
    }
    
  }

  public static void exchange(int[] array, int start, int end) {

  }
}

全部评论

相关推荐

fRank1e:吓得我不敢去外包了,但是目前也只有外包这一个实习,我还要继续去吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务