# Selection Sort

## Overview

Selection sort is the most basic way of sorting an Array. We compare each element with its subsequent elements and swap them if one is smaller than the other.

## Complexity

The complexity of selection sort algorithm for worst case, average cases and best cases is O(n2).

## Selection Sort in Java

``````package com.techstackjournal;

public class SelectionSort {

public static void main(String[] args) {

int[] nums = { 10, 4, 9, 3, 1, 5, 8, 2, 7 };
int temp;

for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] > nums[j]) {
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}

for (int i : nums) {
System.out.print(i + " ");
}

}

}``````

## Selection Sort in C language

``````#include <stdio.h>

void sort(int *nums, int len) {
int temp;

for (int i = 0; i < 9; i++) {
for (int j = i + 1; j < 10; j++) {
if (nums[i] > nums[j]) {
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
}

int main() {

int nums[] = { 10, 4, 9, 3, 1, 5, 8, 2, 7, 6 };

printf("Unsorted array:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", nums[i]);
}

printf("\n\nSorted array:\n");
sort(nums, 10);

for (int i = 0; i < 10; i++) {
printf("%d ", nums[i]);
}

return 0;
}
``````

## Selection Sort in C++

``````#include <iostream>

using namespace std;

void sort(int *nums, int len)
{
int temp;

for (int i = 0; i < 9; i++)
{
for (int j = i + 1; j < 10; j++)
{
if (nums[i] > nums[j])
{
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
}

int main()
{

int nums[] = { 10, 4, 9, 3, 1, 5, 8, 2, 7, 6 };

cout<<"Unsorted array:\n";
for (int i = 0; i < 10; i++)
{
cout<<nums[i]<<" ";
}

cout<<"\n\nSorted array:\n";
sort(nums, 10);

for (int i = 0; i < 10; i++)
{
cout<<nums[i]<<" ";
}

return 0;
}``````