2006程式設計競賽第二題

題目:
Please write a program to input n (max. 20)
numbers and find the medium. 

程式碼:
import java.util.*;
/***************************************
Please write a program to input n (max. 20)
numbers and find the medium. 
*****************************************/

public class E2006_2{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String s = sc.nextLine();//輸入數字
            System.out.println("Please input numbers:"+s);
            int [] Arr = StringToInt(s);
            SelectSort(Arr);
            System.out.println("The medium is : "+medium(Arr));
        }
        
    }

    /*將字串陣列轉整數陣列 */
    public static int[] StringToInt(String s){
        String [] arr = s.split(" ");
        int[] Arr = new int[arr.length];
        for (int i=0; i < arr.length; i++) {
            Arr[i] = Integer.parseInt(arr[i]);
        }
        return Arr;
    }
    /*排序*/
    public static void SelectSort(int arr []){
        int i,j,max;
        int n = arr.length;
        for(i=0;i<n-1;i++){
            max=i; 
        /*找出這陣列比arr[max]小然後交換*/ 
            for(j=i+1;j<n;j++){
                if(arr[max]>arr[j]){ //初始設定arr[max]最大 
                    max = j;
                }
            }
            /*交換*/
            int temp = arr[max];
            arr[max] = arr[i];
            arr[i] = temp;
        }
    }

    /*回傳中間值*/
    public static int medium(int arr []){
        int n = arr[arr.length/2];
        return n;
    }
}

Ex:

Please input numbers: 5 3 10
The medium is : 5
Please input numbers: 7 10 1 8
The medium is : 8
Please input numbers: 2 8 10 3 1
The medium is : 3 

留言

熱門文章