程式設計基礎知識點之排序:氣泡排序法,選擇排序法
阿新 • • 發佈:2019-01-28
public class Demo2{
public static void main(String[] args){
//建立陣列arr
int[] arr = {1,9,5,7,3,2,6};
//輸出原陣列序列
System.out.println("=============================\n原陣列序列:");
for(int in : arr){
System.out.print(in+" ");
}
System.out.println();
//冒泡法排序
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr.length-i-1;j++){
if(arr[j]<arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
//輸出冒泡法排序後陣列
System.out.println("氣泡排序後陣列序列:");
for(int in : arr){
System.out.print(in+" ");
}
System.out.println();
//建立陣列arr2
int[] arr2 = {1,9,5,7,3,2,6};
//輸出原陣列序列
System.out.println("=============================\n原陣列序列:");
for(int in : arr2){
System.out.print(in+" ");
}
System.out.println();
//選擇排序法
for(int i=0;i<arr2.length;i++){
int max = arr2[i];
for(int j = i;j<arr2.length-1;j++){
if(max<arr2[j+1]){
int temp = max;
max = arr2[j+1];
arr2[j+1] = temp;
}
}
arr2[i] = max;
}
//輸出選擇法排序後陣列
System.out.println("選擇排序後陣列序列:");
for(int in : arr2){
System.out.print(in+" ");
}
System.out.println();
}
}
public static void main(String[] args){
//建立陣列arr
int[] arr = {1,9,5,7,3,2,6};
//輸出原陣列序列
System.out.println("=============================\n原陣列序列:");
for(int in : arr){
System.out.print(in+" ");
}
System.out.println();
//冒泡法排序
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr.length-i-1;j++){
if(arr[j]<arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
//輸出冒泡法排序後陣列
System.out.println("氣泡排序後陣列序列:");
for(int in : arr){
System.out.print(in+" ");
}
System.out.println();
//建立陣列arr2
int[] arr2 = {1,9,5,7,3,2,6};
//輸出原陣列序列
System.out.println("=============================\n原陣列序列:");
for(int in : arr2){
System.out.print(in+" ");
}
System.out.println();
//選擇排序法
for(int i=0;i<arr2.length;i++){
int max = arr2[i];
for(int j = i;j<arr2.length-1;j++){
if(max<arr2[j+1]){
int temp = max;
max = arr2[j+1];
arr2[j+1] = temp;
}
}
arr2[i] = max;
}
//輸出選擇法排序後陣列
System.out.println("選擇排序後陣列序列:");
for(int in : arr2){
System.out.print(in+" ");
}
System.out.println();
}
}