class SelectionSortExample {
public void selectionSort(arr) {
def length = arr.length
def lastPriorIndex = length - 2
for (i in 0..lastPriorIndex) {
def minIndex = i
for (j in (i+1)..(length - 1)) {
if(arr[minIndex] > arr[j]) {
minIndex = j
}
}
def temp = arr[minIndex]
arr[minIndex] = arr[i]
arr[i] = temp
}
}
public void printArray(arr) {
def lastIndex = arr.length - 1
for (i in 0..lastIndex) {
def num = arr[i]
print(num + " ")
}
println("")
}
public static void main(String[] args) {
def obj = new SelectionSortExample()
def arr = [15, 3, 12, 6, -9, 9, 0].toArray()
print("Before Sorting: ")
obj.printArray(arr)
obj.selectionSort(arr)
print("After Sorting: ")
obj.printArray(arr)
}
}
出力
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
広告
例を順に追ってみよう
[15, 3, 12, 6, -9, 9, 0] から始めます。
添字0から始めます。残りの値を調べて、最小値(−9)がどの位置にあるかを覚えておきます。
−9と先頭の値15を入れ替えます。これで先頭の位置が確定しました。
次の位置から同じ手順を繰り返します。一つだけ残った時点で、配列全体の並べ替えが終わっています。
Groovy の選択ソートを順に解説
Groovy のソースコード
class SelectionSortExample {
public void selectionSort(arr) {
// Get the length of an array
def length = arr.length
// Loop all the element in an array except the last element (i.e. lastPriorIndex = length - 2)
def lastPriorIndex = length - 2
for (i in 0..lastPriorIndex) {
def minIndex = i
// Find an index of a lowest element in the right-hand side
// corresponding to the element arr[i].
for (j in (i+1)..(length - 1)) {
if(arr[minIndex] > arr[j]) {
minIndex = j
}
}
// Swap the lowest element with the current element (i.e. arr[i] <=> arr[minIndex])
def temp = arr[minIndex]
arr[minIndex] = arr[i]
arr[i] = temp
}
}
public void printArray(arr) {
// Loop the item and print each item in the console with white space seperated
def lastIndex = arr.length - 1
for (i in 0..lastIndex) {
def num = arr[i]
print(num + " ")
}
println("")
}
public static void main(String[] args) {
def obj = new SelectionSortExample()
def arr = [15, 3, 12, 6, -9, 9, 0].toArray()
print("Before Sorting: ")
obj.printArray(arr)
obj.selectionSort(arr)
print("After Sorting: ")
obj.printArray(arr)
}
}
出力
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15