Example 1: selection sort
#include <bits/stdc++.h>
using namespace std;
void selectionSort(int arr[], int n){
int i,j,min;
for(i=0;i<n-1;i++){
min = i;
for(j=i+1;j<n;j++){
if(arr[j] < arr[min]){
min = j;
}
}
if(min != i){
swap(arr[i],arr[min]);
}
}
}
int main()
{
int arr[] = { 1,4,2,5,333,3,5,7777,4,4,3,22,1,4,3,666,4,6,8,999,4,3,5,32 };
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
for(int i = 0; i < n; i++){
cout << arr[i] << " ";
}
return 0;
}
Example 2: selection sort
void selectionSort(int arr[], int n)
{
for(int i = 0; i < n-1; i++)
{
int min = i;
for(int j = i+1; j < n; j++)
{
if(arr[j] < arr[min])
min = j;
}
if(min != i)
{
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}
Example 3: selection sort
procedure selection sort
list : array of items
n : size of list
for i = 1 to n - 1
min = i
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
if indexMin != i then
swap list[min] and list[i]
end if
end for
end procedure
Example 4: Selection sort
SelectionSort(List) {
for(i from 0 to List.Length) {
SmallestElement = List[i]
for(j from i to List.Length) {
if(SmallestElement > List[j]) {
SmallestElement = List[j]
}
}
Swap(List[i], SmallestElement)
}
}
Example 5: selection sort
void sort(int *arr, int n){
for (int i = 0; i < n-1; i++)
{
int indice_min = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[indice_min])
indice_min = j;
}
swap(arr,indice_min,i);
}
}
void swap(int *arr, int a , int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}