【陣列排序】 -選擇排序和氣泡排序
阿新 • • 發佈:2018-11-21
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); //輸入陣列長度 int a [] = new int[n]; for (int i=0;i<n;i++){ //為陣列賦值 int x=input.nextInt(); a[i]=x; } //排序前,先把內容打印出來 for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(" "); //移動的位置是從0 逐漸增加的 //所以可以在外面套一層迴圈 for (int j = 0; j < a.length-1; j++) { for (int i = j+1; i < a.length; i++) { if(a[i]<a[j]){ int temp = a[j]; a[j] = a[i]; a[i] = temp; } } } //把內容打印出來 for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(" "); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); //輸入陣列長度 int a [] = new int[n]; for (int i=0;i<n;i++){ //為陣列賦值 int x=input.nextInt(); a[i]=x; } for (int j = 0; j < a.length; j++) { for (int i = 0; i < a.length-j-1; i++) { if(a[i+1]<a[i]){ int temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } } } //把內容打印出來 for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(" "); } }
public class Main { public static void main(String[] args) { int[] arr=new int[5]; for (int i=0;i<5;i++){ arr[i]=(int)(Math.random()*100); } for (int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } System.out.println(); System.out.println("-----選擇排序----"); //選擇正排序 即是從小到大排序 for (int j=0;j<arr.length-1;j++){ for (int i=j+1;i<arr.length;i++){ if (arr[i]<arr[j]){ int temp=arr[j]; arr[j]=arr[i]; arr[i]=temp; } } } for (int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } System.out.println(); System.out.println("-----氣泡排序----"); for(int j=0;j<arr.length;j++){ for ( int i=0;i<arr.length-j-1;i++){ if(arr[i+1]<arr[i]){ int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } } for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } } }