function sort(list) var sorted = [] while list.length > 0 min = 取出 list 中最小元素 sorted.add(min) end while list = sorted end function
In-place
1 2 3 4 5 6 7 8 9 10 11 12 13
function sort(list) for i = 0; i < list.length - 1; ++i minIndex = i; for j = i + 1; j < list.length; ++j if list[j] < list[minIndex] minIndex = j; end if end for if minIndex != i swap(list[minIndex], list[i]); end if end for end function
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespaceSelectionSort { classExtraSpace { publicstaticvoidSort(int[] array) { List<int> sorted = new List<int>(array.Length); List<int> unsorted = array.ToList(); while (unsorted.Count > 0) { int n = ExtractMin(unsorted); sorted.Add(n); } sorted.ToArray().CopyTo(array, 0); }
privatestaticintExtractMin(List<int> unsorted) { int index = 0, min = unsorted[0]; for (int i = 0; i < unsorted.Count; ++i) { if (unsorted[i] < min) { index = i; min = unsorted[i]; } } unsorted.RemoveAt(index); return min; } } }
voidExtraSpace::Sort(int* array, int length) { vector<int> sorted; vector<int> unsorted(length); for(int i = 0; i < length; i++) unsorted[i] = array[i]; while (unsorted.size() > 0) { int n = ExtraSpace::ExtractMin(unsorted); sorted.push_back(n); } memcpy(array, &sorted[0], sizeof( int ) * sorted.size()); }
intExtraSpace::ExtractMin(vector<int>& unsorted) { int index = 0, min = unsorted[0]; for (int i = 0; i < unsorted.size(); ++i) { if (unsorted[i] < min) { index = i; min = unsorted[i]; } } unsorted.erase(unsorted.begin() + index); return min; }