下面是我的實現選擇排序的:的Java:選擇排序我的實現與另一
package algorithm.selectionsort;
public class SelectionSort {
public static void main(String[] args) {
int[] myArray = selectionSort(new int[] { 9, 9, 9, 8, 7, 73, 32, 109, 1100, 432, 321, 0 });
for (int element : myArray) {
System.out.print("" + element + " ");
}
}
public static int[] selectionSort(int[] a) {
int min;
for (int i = 0; i < a.length - 1; i++) {
min = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
int temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
}
return a;
}
}
我發現我的導師代碼它略有不同:
public static int[] selectionSort(int[] a) {
int min;
for (int i = 0; i < a.length - 1; i++) {
min = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
}
}
int temp = a[i];
a[i] = a[min];
a[min] = temp;
}
return a;
}
兩種實施工作。我很好奇這裏有什麼不同。效率如何?
我明白了 - 我不必要地一遍又一遍地重複相同的代碼。效果是一樣的,但這會讓我放慢抓取龐大的數據集。 –
你的老師實現了選擇排序,你發明了另一種看起來非常相似但效率較低的排序。 – alfasin
https://codereview.stackexchange.com – nullpointer