# Selection Sort: A Graphical Explanation

Sorting rearranges the elements in a list into either ascending or descending order. (we’ll use ascending order.) In this article, we’ll explain the working of Selection sort. Selection Sort divides the array into two parts: already sorted, and not yet sorted. On each pass, it finds the smallest of the unsorted elements, and swaps it into its correct place, thereby increasing the number of sorted elements by one. Selection sort has simplicity, and also has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

## Selection Sort Example

### Selection Sort: Pass One

### Selection Sort: Pass Two

### Selection Sort: Pass Three

### Selection Sort: Pass Four

### Selection Sort: How many comparisons?

The number of comparisons when the array contains N elements is

Sum = (N-1) + (N-2) + . . . + 2 + 1

Although, the number of comparisons are same as bubble sort, however, number of swaps are decreased. Total No. of swaps in Selection sort are: (N -1) , where N = size of array.

## Selection sort implementation in C++

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

### Related Posts

- Bubble Sort: A Graphical Explanation
- Linked lists in C++
- Doubly Linked Lists
- Queue Implementation in C++
- Insertion Sort: A Graphical Explanation
- Applications of Stack in Data Structures
- Circular Linked Lists
- Binary Trees and Binary Search Trees
- Operations on Binary Search Trees (BST)
- Heap data structure in C++
- This Pointer, Static Members and destructors in C++
- Comparison of Sorting Algorithms – Bubble Sort, Selection Sort, Insertion Sort

### Popular Posts (last 30 days)

- Applications of Stack in … 1095 view(s)
- Circular Linked Lists 1041 view(s)
- Attendance Management Sys… 864 view(s)
- Simple Currency Converter… 650 view(s)
- Recursive Factorial funct… 571 view(s)
- Implementing Stack Data S… 560 view(s)
- Graph Implementation in C… 512 view(s)
- Finding Minimum, Maximum … 440 view(s)
- GRASP Design Patterns 300 view(s)
- Finding Maximum Number in… 299 view(s)

### Related Links

### Tags

Android C-Sharp C/C++ language Classes Data structures Design Pattern Eclipse Game Development Graphics Design Books HTML iPhone JAVA JAVA GUI MIPS Assembly Mobile Programming Books Object Oriented PDF PHP Programming Programming Books Programming Languages Books Python RaphaelJS REST Source Code Threads Tutorial Web Development Books