- C++ Programming Examples
- C++ Programming Examples
- C++ Hello World
- C++ Get Input
- C++ Print Integer
- C++ Add Two Numbers
- C++ Add Sub Mul Div
- C++ Add Digits
- C++ Find Average Perc
- C++ Find Arithmetic Mean
- C++ Sum of n Natural Numbers
- C++ Sum of n Numbers
- C++ Area Perimeter of Square
- C++ Area Perimeter of Rectangle
- C++ Area Perimeter of Triangle
- C++ Area Circum of Circle
- C++ Find Simple Interest
- C++ Fahrenheit to Celsius
- C++ Celsius to Fahrenheit
- C++ Print Prime Numbers
- C++ Reverse a Number
- C++ Swap Two Numbers
- C++ Print Multiplication Table
- C++ Find Factorial of Number
- C++ Find Factors of Number
- C++ Find HCF & LCM
- C++ Make Calculator
- C++ Count Digits in Number
- C++ Sum of First & Last Digit
- C++ Product of Digits of Number
- C++ Sum of Squares of Digits
- C++ Interchange Digits of Number
- C++ if else Programs
- C++ Check Even or Odd
- C++ Check Prime or Not
- C++ Check Alphabet or Not
- C++ Check Vowel or Not
- C++ Check Leap Year or Not
- Check Reverse equal Original
- C++ Check Perfect Number
- C++ Check Palindrome or Not
- C++ Check Armstrong or Not
- C++ Divisibility Test
- C++ Find Wage of Labor
- C++ Find Discounted Price
- C++ Find Shipping Charge
- C++ Find Telephone Bills
- C++ Calculate Student Grade
- C++ Largest of Two Numbers
- C++ Largest of Three Numbers
- C++ Number Conversion
- C++ Decimal to Binary
- C++ Decimal to Octal
- C++ Decimal to Hexadecimal
- C++ Binary to Decimal
- C++ Binary to Octal
- C++ Binary to Hexadecimal
- C++ Octal to Decimal
- C++ Octal to Binary
- C++ Octal to Hexadecimal
- C++ Hexadecimal to Decimal
- C++ Hexadecimal to Binary
- C++ Hexadecimal to Octal
- C++ Pattern Programs
- C++ Pattern Programs
- C++ Print Diamond Pattern
- C++ Print Floyd's Triangle
- C++ Print Pascal's Triangle
- C++ Array Programs
- C++ 1D Array Program
- C++ Linear Search
- C++ Binary Search
- Find Largest Element in Array
- Find Smallest Element in Array
- Find Second Largest Element
- Find Second Smallest Element
- C++ Sum of All Elements
- C++ Multiply All Elements
- C++ Element on Even Position
- C++ Element on Odd Position
- C++ Print Even Numbers in Array
- C++ Print Odd Numbers in Array
- C++ Count Even/Odd Numbers
- C++ Sum of Even/Odd Numbers
- C++ Count Positive Negative Zero
- C++ Reverse an Array
- C++ Insert Element in Array
- C++ Delete Element from Array
- C++ Merge two Arrays
- C++ Bubble Sort
- C++ Selection Sort
- C++ Insertion Sort
- C++ Common Elements
- C++ 2D Array Programs
- C++ Add Two Matrices
- C++ Subtract Two Matrices
- C++ Transpose Matrix
- C++ Multiply Two Matrices
- C++ 3D Array Programs
- C++ String Programs
- C++ Print String
- C++ Find Length of String
- C++ Compare Two Strings
- C++ Copy String
- C++ Concatenate String
- C++ Reverse a String
- C++ Delete Vowels from String
- C++ Delete Word from String
- C++ Count Character in String
- C++ Count Word in String
- C++ Frequency of Word
- C++ Remove Spaces from String
- C++ Sort a String
- C++ Uppercase to Lowercase
- C++ Lowercase to Uppercase
- C++ Swap Two Strings
- C++ Check Anagram or Not
- C++ Capitalize All Words in String
- C++ Capitalize Specific Character
- C++ Get Numbers from String
- C++ File Programs
- C++ Read a File
- C++ Write Content to File
- C++ Append Data in File
- C++ Read & Display File
- C++ Copy a File
- C++ Merge Two Files
- Count Characters, Words in File
- C++ Capitalize All Words in File
- C++ List Files in Directory
- C++ Delete a File
- C++ Encrypt & Decrypt a File
- C++ Misc Programs
- C++ Print ASCII Value
- C++ Add Binary Numbers
- C++ Generate Random Numbers
- C++ Print Smiling Face
- C++ Days into Years, Months
- Add Two Numbers using Pointer
- C++ Print Fibonacci Series
- Generate Armstrong Numbers
- C++ Find nCr and nPr
- C++ Get IP Address
- C++ Print Date/Time
- C++ Shutdown, Restart Computer
- C++ Programming Tutorial
- C++ Tutorial
- C++ Programming Test
- C++ Programming Test
- Give Online Test
- All Test List
C++ Program for Selection Sort
In this article, you will learn and get code to implement selection sort in C++. Here are the list of programs on selection sort, available in this article:
- Selection Sort in Ascending Order
- Selection Sort in Descending Order
- Selection Sort using Function
- Selection Sort using Class and Object
But before creating these programs, if you're not aware about selection sort, refer to selection sort algorithm and example to get every required things about it.
Selection Sort in C++
To sort an array in ascending order using selection sort technique in C++ programming, you have to ask from user to enter the size and elements for an array. Now sort the array using selection sort technique as shown in the program given below:
Note - Selection sort works in a way that, initially the smallest element gets selected and moved to very first index (0th index, because indexing in arrays starts from 0), then second smallest element gets selected and moved to second (1st) index and so on.
#include<iostream> using namespace std; int main() { int tot, arr[50], i, j, temp, small, chk, index; cout<<"Enter the Size of Array: "; cin>>tot; cout<<"Enter "<<tot<<" Array Elements: "; for(i=0; i<tot; i++) cin>>arr[i]; for(i=0; i<(tot-1); i++) { chk=0; small = arr[i]; for(j=(i+1); j<tot; j++) { if(small>arr[j]) { small = arr[j]; chk++; index = j; } } if(chk!=0) { temp = arr[i]; arr[i] = small; arr[index] = temp; } } cout<<"\nSorted Array is:\n"; for(i=0; i<tot; i++) cout<<arr[i]<<" "; cout<<endl; return 0; }
This program was build and run under Code::Blocks IDE. Here is its sample run:
Now enter the size say 10 and then enter any 10 array elements say
10, 1, 9, 2, 8, 3, 7, 4, 6, 5 and press
ENTER
key to sort the array using selection sort technique, and then print new sorted array as shown in
the snapshot given below:
The dry run of above program with same user input as provided in above sample run, goes like:>
- When user enters 10 as size, then it gets stored in tot. So tot=10
- And when user enters 10 elements, then it gets stored in arr in this way:
- arr[0]=10
- arr[1]=1
- arr[2]=9
- and so on upto
- arr[9]=5
- Now the execution of second for loop of the program, or the loop that is created to perform the selection sort, begins
- That is, 0 gets initialized to i and the condition i<(tot-1) or 0<(10-1) or 0<9 evaluates to be true, therefore program flow goes inside the loop
- Inside the loop, 0 gets initialized to chk. So chk=0
- And arr[i] or arr[0] or 10 gets initialized to small. So small=10, we've assumed 10 as the smallest element. Now let's compare it with elements at rest indexes
- Every time we've supposed the element at current index as the smallest element, then compared it with rest of the element, if it is found greater than any element, then we've initialized a new element as the smallest one
- Now the execution of inner for loop begins. That is, (i+1) or 0+1 or 1 gets initialized to j, and the condition j<tot or 1<10 evaluates to be true, therefore program flow goes inside the loop
- Inside this loop, the condition (of if) small>arr[j] or 10>arr[1] or 10>1 evaluates to be true, therefore program flow goes inside the if's body
- And arr[j] or arr[1] or 1 gets initialized to small. The value of chk gets incremented. So chk=1. And finally j or 1 gets initialized to index
- Now the value of j gets incremented. So j=2 and the condition j<tot or 2<10 evaluates to be true again, therefore program flow again goes inside the loop. This process continues until the condition of this for loop evaluates to be false
- Because, 1 is the smallest element, therefore small=1 after exiting from this loop. And 1 is at 1st index, therefore index=1
- After exiting from this loop, the condition (of if) chk!=0 or 1!=0 evaluates to be true, therefore arr[i] or arr[0] or 10 gets initialized to temp, small or 1 gets initialized to arr[i] or arr[0], and finally temp or 10 gets initialized to arr[index] or arr[1]
- Now the program flow goes to the update part of outer for loop and increments the value of i. So i=1. And the condition again gets evaluated
- That is the condition i<(tot-1) or 1<(10-1) or 1<9 evaluates to be true again, therefore program flow again goes inside the loop
- This process continues until the condition evaluates to be false
- In this way, selection sort gets implemented
To print array after each sort, just place the following block of code:
cout<<"Step "<<i+1<<": "; for(j=0; j<tot; j++) cout<<arr[j]<<" "; cout<<endl;
after
if(chk!=0) { temp = arr[i]; arr[i] = small; arr[index] = temp; }
That is, place the code at last inside the for loop that is created to perform selection sort. Now the sample run with same user input as provided in previous sample run, looks like:
Selection Sort in Descending Order
To sort an array in descending order using selection sort technique, only replace the condition of if. That is, replace the following condition:
small>arr[j]
with the condition given below
small<arr[j]
Note - Just a matter of greater than (>) and less than (<) sign, whole program gets reversed.
But still, if you want the complete program for selection sort in descending order, then here it is:
#include<iostream> using namespace std; int main() { int tot, arr[50], i, j, temp, big, chk, index; cout<<"Enter the Size of Array: "; cin>>tot; cout<<"Enter "<<tot<<" Array Elements: "; for(i=0; i<tot; i++) cin>>arr[i]; for(i=0; i<(tot-1); i++) { chk=0; big = arr[i]; for(j=(i+1); j<tot; j++) { if(big<arr[j]) { big = arr[j]; chk++; index = j; } } if(chk!=0) { temp = arr[i]; arr[i] = big; arr[index] = temp; } } cout<<"\nSorted Array in Descending Order is:\n"; for(i=0; i<tot; i++) cout<<arr[i]<<" "; cout<<endl; return 0; }
The snapshot given below shows the sample run of this program with user input, 10 as size, and 1, 10, 9, 2, 8, 3, 7, 4, 6, 5 as 10 array elements:
Selection Sort using Function
Now let's create another program that does the same job as of very first program. That is this program implements selection sort to sort an array in ascending order, using user-defined function selSort().
The function selSort() takes two arguments. The first argument is the array, whereas the second argument is its size. This function sorts an array using selection sort technique:
#include<iostream> using namespace std; void selSort(int [], int); int main() { int tot, arr[50], i; cout<<"Enter the Size of Array: "; cin>>tot; cout<<"Enter "<<tot<<" Array Elements: "; for(i=0; i<tot; i++) cin>>arr[i]; selSort(arr, tot); cout<<"\nSorted Array is:\n"; for(i=0; i<tot; i++) cout<<arr[i]<<" "; cout<<endl; return 0; } void selSort(int arr[], int tot) { int i, j, temp, small, chk, index; for(i=0; i<(tot-1); i++) { chk=0; small = arr[i]; for(j=(i+1); j<tot; j++) { if(small>arr[j]) { small = arr[j]; chk++; index = j; } } if(chk!=0) { temp = arr[i]; arr[i] = small; arr[index] = temp; } } }
This program produces the same output as of very first program of this article. Here is its sample run, with user input 5 as size, and 5, 4, 3, 2, 1 as 5 array elements:
Selection Sort using Class
This is the last program of this article to implement selection sort in C++. This program uses class and object, an object-oriented feature of C++.
#include<iostream> using namespace std; class CodesCracker { public: void selSort(int [], int); }; void CodesCracker::selSort(int arr[], int tot) { int i, j, temp, small, chk, index; for(i=0; i<(tot-1); i++) { chk=0; small = arr[i]; for(j=(i+1); j<tot; j++) { if(small>arr[j]) { small = arr[j]; chk++; index = j; } } if(chk!=0) { temp = arr[i]; arr[i] = small; arr[index] = temp; } } } int main() { CodesCracker c; int tot, arr[50], i; cout<<"Enter the Size of Array: "; cin>>tot; cout<<"Enter "<<tot<<" Array Elements: "; for(i=0; i<tot; i++) cin>>arr[i]; c.selSort(arr, tot); cout<<"\nSorted Array is:\n"; for(i=0; i<tot; i++) cout<<arr[i]<<" "; cout<<endl; return 0; }
An object c is created of type CodesCracker inside the main() function. And using this object, we've called the member function (selSort()) of the class CodesCracker using dot (.) operator. Rest of the things are similar like function.
Same Program in Other Languages
« Previous Program Next Program »