- C Programming Examples
- C Programming Examples
- C Print Hello World
- C Get Input from User
- C Print Integer
- C Add Two Numbers
- C Add Subtract Multiply Divide
- C Add n Numbers
- C Area Perimeter of Square
- C Area Perimeter of Rectangle
- C Area Circum of Circle
- C Fahrenheit to Celsius
- C Celsius to Fahrenheit
- C Inches to Centimeters
- C Kilogram to Gram
- C Reverse a Number
- C Swap Two Numbers
- C Interchange Numbers
- C Print ASCII Value
- C Print Fibonacci Series
- C Check Palindrome or Not
- C Check Armstrong or Not
- C Find Armstrong Numbers
- C Find nCr and nPr
- C Find Profit Loss
- C Sum of their Square
- C First & Last Digit Sum
- C Sum of All Digit
- C Product of All Digit
- C Print Total Digit in Number
- C Check Perfect Number
- C Find Basic Gross Salary
- C Round Number to Integer
- C Print Series upto n Term
- C Find Factors of Number
- C if-else & Loop 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
- C Is Reverse Equal Original
- C Make Calculator
- C Add Digits of Number
- Count Positive Negative Zero
- C Largest of Two Numbers
- C Largest of Three Numbers
- C Smallest of Two Numbers
- C Smallest of Three Numbers
- C Find Factorial of Number
- C Find LCM & HCF
- C Find LCM of n Numbers
- C Find HCF of n Numbers
- C Find Arithmetic Mean
- C Find Average, Percentage
- C Find Student Grade
- C Print Table of Number
- C Print Prime Numbers
- C Find Discount Purchase
- C Calculate Parcel Charge
- C Calculate Wage of Labor
- C Print Phone Bill
- C Conversion programs
- 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 Printing Programs
- C Print Diamond Pattern
- C Print Floyd's Triangle
- C Print Pascal's Triangle
- C Array Programs
- C 1D Array Programs
- C Linear Search
- C Binary Search
- C Largest Element in Array
- C Smallest Element in Array
- C Second Largest/Smallest
- C Count Even Odd
- C Array Element at Even
- C Array Element at Odd
- C Print Even Array Elements
- C Print Odd Array Elements
- C Sum/Product of Even/Odd
- 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 Print Common Elements
- C 2D Array Programs
- C Add Two Matrices
- C Subtract Two Matrices
- C Transpose a Matrix
- C Multiply Two Matrices
- C Sum All Matrix Elements
- C Largest Element in Matrix
- C Print Row Column Total
- C 3D Array Programs
- C String Programs
- C Print String
- C Find Length of String
- C Compare Two String
- C Copy a String
- C Concatenate String
- C Reverse a String
- C Count Vowels Consonants
- C Replace Vowel in String
- C Delete Vowels from String
- C Delete Word from String
- C Frequency of Character
- C Count Word in String
- C Remove Spaces from String
- C Sort a String
- C Sort String in Alphabetical
- C Sort Words in Ascending
- C Sort Words in Descending
- C Uppercase to Lowercase
- C Lowercase to Uppercase
- C Swap Two Strings
- C Check Anagram or Not
- C Check Palindrome String
- C Print Number in Words
- C Print Successive Character
- C Character without Space
- C File Programs
- C Read a File
- C Write Content to File
- C Read & Display File
- C Copy a File
- C Merge Two Files
- C Reverse File
- C Count All Character in File
- C List Files in Directory
- C Encrypt & Decrypt a File
- C Delete a File
- C Misc Programs
- Generate Random Numbers
- C Print Date Time
- C Print Message with Time
- C Get IP Address
- C Print Smiling face
- C Pass Array to Function
- Add Two Numbers using Pointer
- C Address of Variable
- C Shutdown Computer
- C Programming Tutorial
- C Tutorial
C Program for Selection Sort
In this tutorial, we will learn how to create a program in C that sorts an array using the selection sort technique. At last, we have also created a function that can be used to sort any given array in ascending order using the selection sort technique.
But before going through the program, if you are not aware of how selection sort works, refer to the step-by-step workings of selection sort. Now let's move on and implement it in a C program.
Selection sort in C
To sort an array in ascending order using the selection sort technique in C programming, you have to ask the user to enter the array's size and its elements. Then apply the selection sort mechanism and print the sorted array as output, just like the program given below:
#include<stdio.h> #include<conio.h> int main() { int size, arr[50], i, j, temp, small, count=0, index; printf("Enter size for Array: "); scanf("%d", &size); printf("Enter %d array elements: ", size); for(i=0; i<size; i++) scanf("%d", &arr[i]); for(i=0; i<(size-1); i++) { small = arr[i]; for(j=(i+1); j<size; j++) { if(small>arr[j]) { small = arr[j]; count++; index = j; } } if(count!=0) { temp = arr[i]; arr[i] = small; arr[index] = temp; } count=0; } printf("\nNow the Array after sorting is:\n"); for(i=0; i<size; i++) printf("%d ", arr[i]); getch(); return 0; }
As the above program was written in the Code::Blocks IDE, here is the sample run after a successful build and run. This is the first snapshot of the sample run:
Now enter the array size, say 5, and its elements as 54, 21, 8, 18, and 3, and press the ENTER key to see the sorted array shown in the second snapshot of the sample run provided here:
Here is another sample run. This is the final snapshot:
C Selection Sort Program Explained
- At runtime, get the array size from the user.
- Then receive elements of that size for the array at run-time.
- For example, if the user has supplied 5 as the array size, then ask him or her to enter 5 array elements.
- Create a for loop that runs from 0 to one less than the size of the array. That is, if the array's size is 5, then run the loop from 0 to one less than 5-1 or 4.
- Set the element at the current index to a variable, let's call it "small," inside the loop.
- And using another for loop (which runs from 0 to one less than the size of the array), check whether the value in the small variable is greater than any element (present at index equals to the value of i+1 to size-1 or 4) or not.
- If it is, set that element to a "small" variable and increase the "count" variable. Then, set the current value of j (the inner loop variable) to the "index" variable, which holds the index number where the smallest element appears.
- Never forget to initialize the "count" (with 0) variable at the start of the program.
- Now, after exiting from the inner for loop, check whether count holds any value other than 0 or not.
- If it holds any value other than 0, then program flow has gone inside the if statement of the inner for loop. And it means that any element that was initialized to the "small" variable.
- Therefore, we have to perform a swapping operation, that is, place the element at the beginning of any variable, say "temp," and then initialize the value of "small" at the beginning. At the end, the value of "temp" is initialized at the index from where the element was initialized to the "small" variable before swapping.
- After swapping, initialize 0 to the "count" variable and continue.
- For example, if the user has entered 5 as the array size and "54 21 8 18 3" as its elements.
- Then, at the first run of the "for" loop, "i" holds 0. Furthermore, "i<(size-1)" or "0<0(5-1)" or "0<4" evaluates to true. Therefore, program flow goes inside the loop.
- The value at "arr[0]" or "54" gets initialized to "small." Therefore, "small" holds 54
- Now, in the inner "for" loop, the value of "i+1" (0+1) or "1" gets initialized to "j" (the inner loop's variable). Therefore, "j" holds 1, and 1 is less than "size" or "5". Therefore, program flow goes inside the inner "for" loop.
- Now the statement "small>arr[j]" or "54>arr[1]" or "54>21" is evaluated to be true, therefore "arr[j]" or "arr[1]" or "21" gets initialized to "small". The value of "count" gets incremented and becomes 1, and the value of "j" or "1" gets initialized to "index."
- Again the value of "j" gets incremented and compared to see whether "j" is less than "size" or not, that is "j (2)" is less than "size(5)", therefore again program flow goes inside the loop.
- And again, "small>arr[j]" or "21>arr[2]" or "21>8" evaluates to true, therefore, after swapping
- The variable "small" holds "8," "count" holds "2," "index" holds "2."
- Again the value of "j" gets incremented and compared to see whether "j" is less than "size" or not, that is "j (3)" is less than "size(5)," therefore again program flow goes inside the loop.
- And again, "small>arr[j]" or "8>arr[3]" or "8>18" evaluates to false, therefore, no swapping gets performed.
- The variable "small" holds "8," "count" holds "2," "index" holds "2."
- Again the value of "j" gets incremented and compared to see whether "j" is less than "size" or not, that is "j (4)" is less than "size(5)", therefore again program flow goes inside the loop.
- And again, "small>arr[j]" or "8>arr[4]" or "8>3" evaluates to true, therefore, after swapping
- The variable "small" holds "3," "count" holds "3," "index" holds "4."
- Again value of "j" gets incremented and compared to determine whether "j" is less than "size" or not, that is, whether "j (5)" is less than "size(5)" or not. Here the condition evaluates to false, and the program flow goes back at the outer "for" loop and increments the value of "i." Then checks the condition to see whether "i" is less than "size-1," "5-1," or "4" or not. It evaluates to true, so the program flow returns to the loop and repeats the preceding steps until the condition of the outer "for" loop is evaluated as false.
If you want to print array elements as a step-by-step sorting of array elements shown on the output screen along with its final array, Then you can modify the above code as shown below to print array elements after each sorting step:
#include<stdio.h> #include<conio.h> int main() { int size, arr[50], i, j, temp, small, count=0, index; printf("Enter size for Array: "); scanf("%d", &size); printf("Enter %d array elements: ", size); for(i=0; i<size; i++) scanf("%d", &arr[i]); for(i=0; i<(size-1); i++) { small = arr[i]; for(j=(i+1); j<size; j++) { if(small>arr[j]) { small = arr[j]; count++; index = j; } } if(count!=0) { temp = arr[i]; arr[i] = small; arr[index] = temp; } printf("\nStep %d: ", i+1); for(j=0; j<size; j++) printf("%d ", arr[j]); printf("\n"); count=0; } printf("\nNow the Array after sorting is:\n"); for(i=0; i<size; i++) printf("%d ", arr[i]); getch(); return 0; }
Here is the final snapshot of the sample run:
C selection sort using a user-defined function
Let's create the same program, which is to sort an array in ascending order using the selection sort technique, but this time with the help of a function. Here selection sort is implemented inside a function named selsort() that uses two arguments, one of which is an array and the other is its size, as shown in the program given below:
#include<stdio.h> #include<conio.h> void selsort(int arr[], int size); int main() { int size, arr[50], i; printf("Enter size for Array: "); scanf("%d", &size); printf("Enter %d array elements: ", size); for(i=0; i<size; i++) scanf("%d", &arr[i]); selsort(arr, size); printf("\nThe sorted Array is:\n"); for(i=0; i<size; i++) printf("%d ", arr[i]); getch(); return 0; } void selsort(int arr[], int size) { int i, j, temp, small, count=0, index; for(i=0; i<(size-1); i++) { small = arr[i]; for(j=(i+1); j<size; j++) { if(small>arr[j]) { small = arr[j]; count++; index = j; } } if(count!=0) { temp = arr[i]; arr[i] = small; arr[index] = temp; } count=0; } }
Here is the final snapshot of the above program:
The concept used in the above program is similar to that used in the first program, except we have implemented the function selsort() here. This function implements all selection sorting techniques. We only have to pass any array and its size as an argument to this function. And all the elements inside the array get sorted in ascending order.
The same program in different languages
« Previous Program Next Program »