iT邦幫忙

0

java選擇排序法

各位大大好,我寫了個小程式,依照選擇排序的概念寫的,想確認是否為選擇排序而不是冒泡排序法。
public static void main(String[] args) {
	int[] n = { 3, 4, 6, 5, 2 };
	for (int i = 0; i < n.length; i++) {
		for (int j = i + 1; j < n.length; j++) {
			if (n[i] > n[j]) {
				int temp = n[i];
				n[i] = n[j];
				n[j] = temp;
			}
		}
	}
	for (int i = 0; i < n.length; i++) {
		System.out.print(n[i] + " ");
	}
}
sleepgary iT邦新手 5 級 ‧ 2019-10-18 13:57:34 檢舉
感謝各位的回答
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
1
海綿寶寶
iT邦大神 1 級 ‧ 2019-10-14 10:42:40
最佳解答

確認你寫的不是選擇排序

選擇排序可以參考資料來源

    public class SelectionSortExample {  
        public static void selectionSort(int[] arr){  
            for (int i = 0; i < arr.length - 1; i++)  
            {  
                int index = i;  
                for (int j = i + 1; j < arr.length; j++){  
                    if (arr[j] < arr[index]){  
                        index = j;//searching for lowest index  
                    }  
                }  
                int smallerNumber = arr[index];   
                arr[index] = arr[i];  
                arr[i] = smallerNumber;  
            }  
        }  
           
        public static void main(String a[]){  
            int[] arr1 = {9,14,3,2,43,11,58,22};  
            System.out.println("Before Selection Sort");  
            for(int i:arr1){  
                System.out.print(i+" ");  
            }  
            System.out.println();  
              
            selectionSort(arr1);//sorting array using selection sort  
             
            System.out.println("After Selection Sort");  
            for(int i:arr1){  
                System.out.print(i+" ");  
            }  
        }  
    }  

選我正解

1
阿展展展
iT邦好手 1 級 ‧ 2019-10-14 03:36:07

(Selection Sort) 是「選擇當中最小的那一個」,再把它塞進新的變數

你的命題當中:「選擇當中最小的那一個」這個動作,你用的方法是 bubble

這....

小魚 iT邦大師 1 級 ‧ 2019-10-14 08:35:02 檢舉

為什麼聽起來還是O(n^2),
沒有比較快啊...

1
小魚
iT邦大師 1 級 ‧ 2019-10-14 08:36:54

你這看起來是氣泡排序吧,
選擇排序你Google一下就知道了,
不過都是O(n^2),
好像也差不多...

1
harry xie
iT邦研究生 1 級 ‧ 2019-10-14 09:33:49

你給的程式是氣泡排序法,關於選擇排序法我之前有寫過一篇文章,不過使用語言是 javascript,但是我想應該還是看得懂9成以上的程式碼,給你參考看看:
https://ithelp.ithome.com.tw/articles/10223748

我要發表回答

立即登入回答