Simple Selection Sort Program using functions in C++
Definition
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.
Example Program
/* Simple Selection Sort Program Using Functions and Array in C++*/
/* Data Structure C++ Programs,C++ Functions and Array Examples */
#include <iostream>
#include<conio.h>
#include<stdlib.h>
#define MAX_SIZE 5
using namespace std;
void selection_sort(int[]);
int main() {
int arr_sort[MAX_SIZE], i;
cout << "Simple C++ Selection Sort Example - Functions and Array\n";
cout << "\nEnter " << MAX_SIZE << " Elements for Sorting : " << endl;
for (i = 0; i < MAX_SIZE; i++)
cin >> arr_sort[i];
cout << "\nYour Data :";
for (i = 0; i < MAX_SIZE; i++) {
cout << "\t" << arr_sort[i];
}
selection_sort(arr_sort);
getch();
}
void selection_sort(int fn_arr[]) {
int i, j, a, t, p;
for (i = 0; i < MAX_SIZE; i++) {
p = i;
for (j = i; j < MAX_SIZE; j++) {
if (fn_arr[p] > fn_arr[j])
p = j;
}
if (p != 1) {
//Swapping Values
t = fn_arr[i];
fn_arr[i] = fn_arr[p];
fn_arr[p] = t;
}
cout << "\nIteration : " << i;
for (a = 0; a < MAX_SIZE; a++) {
cout << "\t" << fn_arr[a];
}
}
cout << "\n\nSorted Data :";
for (i = 0; i < MAX_SIZE; i++) {
cout << "\t" << fn_arr[i];
}
getch();
}
Sample Output
Simple Selection Sort Example - Functions and Array
Enter 5 Elements for Sorting
56
12
34
11
2
Your Data : 56 12 34 11 2
Iteration 0 : 2 12 34 11 56
Iteration 1 : 2 11 34 12 56
Iteration 2 : 2 11 12 34 56
Iteration 3 : 2 11 12 34 56
Iteration 4 : 2 11 12 34 56
Sorted Data : 2 11 12 34 56
------------------
(program exited with code: 0)
Top Pages
- Simple Merge Sort Program in C++
- Scope Resolution Operator In C++
- Simple Program for Virtual Functions Using C++ Programming
- Simple Class Example Program For Find Prime Number In C++
- Simple Example Program For Parameterized Constructor In C++
- Define Constructor in Outside Class Example Program In C++
- Simple Program for Single Inheritance Using C++ Programming
- Simple Example Program For Copy Constructor In C++
- Simple Program for Function Overloading Using C++ Programming
- Simple Example Program For Constructor In C++