Thursday November 7th, 2019

Selection Sort

By Ebubekir Sezer

Hello, Selection Sort is a sorting algorithm. With Selection Sort, we can sort the array minimum to the maximum or maximum to the minimum. Algorithm, choose the first element of the array as minimum and then in the for loops, we controlled the conditions if there is some minimum value than the or minimum then we change the their places. Algorithm is really simple to implement. Algorithms has complexity and complexity of the Selection Sort can find by the using this formula n2.  For the make example about the algorithm, I implement the Selection Sort Algorithm using by the Python and C. In the examples, I sort the array minimum to maximum and maximum to minimum.

C Codes;

#include<stdio.h>

void selectionSort(int array[],int size){
	int min;
	
	for(int i =0;i<size-1;i++){
		min = i;
		
		for(int j = i;j<size;j++){
			if(array[j]<array[min]){
				min = j;
			}
		}
		int temp = array[i];
		array[i] = array[min];
		array[min] = temp;
	}
}

void maxToMin(int array[],int size){
	int max;
	
	for(int i=0;i<size;i++){
		max  = i;
		for(int j=i;j<size;j++){
			if(array[j]>array[max]){
				max= j;
			}
		}
		int temp = array[i];
		array[i] = array[max];
		array[max] = temp;
	}
}

int main(){
	int array[] = {1,3,6,5,7,8,2,4};
	int n = sizeof(array)/sizeof(array[0]);
	selectionSort(array,n);
	for(int i =0;i<n;i++){
		printf("%d ",array[i]);
	}
	printf("\n");
	maxToMin(array,n);
	for(int i =0;i<n;i++){
		printf("%d ",array[i]);
	}
}

Python Codes;

array = [1,3,6,5,7,8,2,4]

for i in range(len(array)):
    min = i
    for j in range(i+1,len(array)):
        if array[min]>array[j]:
            min = j
    array[i],array[min] = array[min],array[i]

print("Selection Sort")
for i in range(len(array)):
    print("%d" %array[i])


for i in range(len(array)):
    max = i
    for j in range(i+1,len(array)):
        if array[j]>array[max]:
            max = j
    
    array[i],array[max] = array[max],array[i]

print("Max to Min")
for i in range(len(array)):
    print("%d " %array[i])

For your questions, you can reach me via e-mail or comments.