0.3.1 输入排序

2019-05-09  本文已影响0人  RockyLuo_290f

查找和排序

题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
都按先录入排列在前的规则处理。

示例:
jack 70
peter 96
Tom 70
smith 67

从高到低 成绩
peter 96
jack 70
Tom 70
smith 67

从低到高

smith 67

jack 70
Tom 70
peter 96


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputSort {
    public static void sort(String[] users, Integer[] scores, int sortType) {
        if(scores == null || scores.length <2) {
            return;
        }
        for(int i =0; i< scores.length-1; i++) {
            String tempUser;
            Integer tempScore;
            for(int j= i+1; j < scores.length; j++) {
                if(((sortType == 0)&&(scores[i] < scores[j])) || ((sortType == 1)&&(scores[i] > scores[j]))){
                    tempUser = users[i];
                    users[i] = users[j];
                    users[j] = tempUser;
                    
                    tempScore = scores[i];
                    scores[i] = scores[j];
                    scores[j] = tempScore;
                    
                }
                
            }
        }
    }
    
    
    public static void main(String[] args){
        BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));
        try {
            String str = null;
            if((str = reader.readLine()) !=null) {
                int count = Integer.parseInt(str);
                int sortType = Integer.parseInt(reader.readLine());
                
                String[] users = new String[count];
                Integer[] scores = new Integer[count];
                for(int i=0; i< count; i++) {
                    String[] lineParts = reader.readLine().split(" ");
                    String user = lineParts[0];
                    Integer score = Integer.parseInt(lineParts[1]);
                    users[i] = user;
                    scores[i] = score;
                }
                sort(users, scores, sortType);

                for(int i=0;i<count;i++){
                    System.out.println(users[i]+" "+scores[i]);
                }
            }
        }catch(IOException e){
            
        }finally{
            
        }
    }

}
上一篇下一篇

猜你喜欢

热点阅读