Java藍橋模擬戰——數列排序:給定一個長度爲n的數列,將這個數列按從小到大的順序排列

資源限制

時間限制:1.0s 內存限制:512.0MB

問題描述

給定一個長度爲n的數列,將這個數列按從小到大的順序排列。1<=n<=200

輸入格式

第一行爲一個整數n。
第二行包含n個整數,爲待排序的數,每個整數的絕對值小於10000。

輸出格式

輸出一行,按從小到大的順序輸出排序後的數列。

樣例輸入

5
8 3 6 4 9

樣例輸出

3 4 6 8 9

提交代碼1——冒泡排序

import java.util.Scanner;

public class Main {
		public static void main(String[] args) {
			Scanner sc = new Scanner(System.in);
			int n = sc.nextInt();
			int  [] a = new int [n] ;
			for(int i = 0 ; i < n ; i++ )
				a[i] = sc.nextInt() ;
			for(int j = 0 ; j < n ; j++ )
			for(int i = 1 ; i < n ; i++ )
				if(a[i] < a[i-1]) {
					int k = a[i-1] ;
					a[i-1] = a[i] ;
					a[i] = k ;
				}
			for(int i = 0 ; i < n ; i++ )
				System.out.print(a[i]+" ");
		}
}

提交代碼2——調用方法

import java.util.*;

public class Main {
		public static void main(String[] args) {
			Scanner sc = new Scanner(System.in);
			int n = sc.nextInt();
			int  [] a = new int [n] ;
			for(int i = 0 ; i < n ; i++ )
				a[i] = sc.nextInt() ;
			Arrays.sort(a); //對數組進行升序排序
			for(int i = 0 ; i < n ; i++ )
				System.out.print(a[i]+" ");
		}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章