配列の最小値と最大値の両方を考慮し、それらを両端に配置する選択ソートの修正版を作成しました
アルゴリズムは次のように機能します
1. Find the minimum and the maximum value in the list.
2. Swap the minimum value with the value in the first position.
3. Swap the maximum value with the value in the last position.
4. Repeat the steps above for the remainder of the list
(starting at the second position and ending at the second to
last position and narrowing the range of positions examined
from both ends of the array each time).
残念ながら、上記は重複値を持つ配列に対して予期しない結果を示しています。
例えば、
[9, 37, 12, 1, 13, 31, 5, 37, 36, 29, 19, 22, 20, 15, -1, 23]
にソートされました
[-1, 1, 5, 9, 12, 13, 15, 19, 20, 22, 23, 29, 31, 37, 36, 37]
実際、ここでの主な問題は、単純に重複に関してだけでなく、一般的にアルゴリズムが配列の後半部分の要素に対して適切なソートを行っていないことです。
ここに私の疑似コードがあります
int i=0;
while(i<=(arr.length-i-1)) {
int minIndex = i;
int maxIndex=arr.length-i-1;
for (int j = i+1; j <=arr.length-i-1; j++) {
if (arr[j] <=arr[minIndex]) {
minIndex = j;
}
if(arr[j]>=arr[maxIndex]){
maxIndex = j;
}
}
swap(arr, i, minIndex);
swap(arr, (arr.length-i-1), maxIndex);
i++;
}
編集これは、アルゴリズムと対話する唯一のものである私のコードのスワップ部分です。変わらないと思いますが一応載せておきます
private static void swap(int[] arr, int oldIndex, int newIndex){
int temp=arr[oldIndex];
arr[oldIndex]=arr[newIndex];
arr[newIndex]=temp;
}