# 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)

- Attendance Management Sys… 1203 view(s)
- Implementing Stack Data S… 596 view(s)
- Graph Implementation in C… 594 view(s)
- Applications of Stack in … 536 view(s)
- Circular Linked Lists 526 view(s)
- Simple Currency Converter… 444 view(s)
- GRASP Design Patterns 330 view(s)
- Advanced Data Structures … 268 view(s)
- C++ Tutorial for Intermed… 260 view(s)
- Sockets and Network Progr… 187 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