Selection sort algorithm and source code

#include<iostream>
#include<conio.h>
using namespace std;

// find the smallest item and place at the front
void selectionSort(int arr[], int size){
	for(int i=0; i< size; i++){
//	Assume first smallest number is at i (i.e first pos)
		int small = i;
		for(int j=i+1; j< size; j++){
//	Compare this position element with the remaining item of the array			
			if(arr[j]<arr[i]){
//	If smallest number found, mark that item position for small				
				small=j;
			}
		}		
//	In this position we found smallest number available in an array and swapping		
		int temp=arr[i];
		arr[i]=arr[small];
		arr[small]=temp;
	}
}

int main(){
	int size=6;
	int arr[size]={1,5,3,2,20,10};
	
selectionSort(arr, size);
	
	for(int i=0; i<size; i++){
		cout<< arr[i] << "\t";
	}
	getch();
	return 0;
}
© 2016 - 2022, All Rights are Reserved.