diff --git a/Sources/Ordering/SelectionSort.swift b/Sources/Ordering/SelectionSort.swift index 4888979..df812cd 100644 --- a/Sources/Ordering/SelectionSort.swift +++ b/Sources/Ordering/SelectionSort.swift @@ -5,3 +5,26 @@ // Created by Brayan Martinez on 28/6/24. // +public func selectionSort(data: inout [Int]) { + for i in 0..<(data.count-1) { + var min_index = i + for j in i + 1..<(data.count) { + if (data[min_index] > data[j]) { + min_index = j + } + } + if (min_index != i) { + swap(first: i, second: min_index, data: &data) + } + } +} + +private func swap(first: Int, second: Int, data: inout [Int]) { + var value1 = data[first] + var value2 = data[second] + let temp = value1 + value1 = value2 + value2 = temp + data[first] = value1 + data[second] = value2 +} diff --git a/Tests/OrderingTest/SelectionSortTest.swift b/Tests/OrderingTest/SelectionSortTest.swift new file mode 100644 index 0000000..98c49c4 --- /dev/null +++ b/Tests/OrderingTest/SelectionSortTest.swift @@ -0,0 +1,30 @@ +// +// SelectionSortTest.swift +// +// +// Created by Brayan Martinez on 30/6/24. +// + +import Testing +@testable import Util +@testable import Ordering + +@Test func selectionSortTest() async throws { + var data: [Int] = getData() + + print("-- SelectionSort -- \n\n") + + //before + print("Before Sorting: \n") + printData(data: &data) + + //sort + print("\n") + selectionSort(data: &data) + + //after + print("After Sorting: \n") + printData(data: &data) + + print("Test Passed!") +}