0% found this document useful (0 votes)
9 views3 pages

Selection Sort

The document provides an implementation of the selection sort algorithm in C++, including user input for the number of elements and the elements themselves. It outlines the steps of the algorithm in both code and pseudocode formats. The program sorts the input array and prints the sorted result.

Uploaded by

brotin2503
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views3 pages

Selection Sort

The document provides an implementation of the selection sort algorithm in C++, including user input for the number of elements and the elements themselves. It outlines the steps of the algorithm in both code and pseudocode formats. The program sorts the input array and prints the sorted result.

Uploaded by

brotin2503
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

SELECTION SORT:::::

#include <iostream>

using namespace std;

void selectionSort(int arr[], int n) {

for (int i = 0; i < n - 1; i++) {

int minIndex = i;

for (int j = i + 1; j < n; j++) {

if (arr[j] < arr[minIndex]) {

minIndex = j;

// Swap the found minimum element with the first element

if (minIndex != i) {

int temp = arr[i];

arr[i] = arr[minIndex];

arr[minIndex] = temp;

int main() {

int n;

cout << "Enter the number of elements: ";

cin >> n;

int arr[n];

cout << "Enter " << n << " elements:" << endl;

for (int i = 0; i < n; i++) {

cin >> arr[i];

selectionSort(arr, n);

cout << "Sorted array: ";

for (int i = 0; i < n; i++) {

cout << arr[i] << " ";

cout << endl;


return 0;

Algorithm for Selection Sort (with user input)

1. Start.

2. Take input for the number of elements in the array (n).

3. Create an array of size n and input n elements from the user.

4. Loop through the array from index i = 0 to n-2.

o Set minIndex = i.

o Loop through the rest of the array (j = i+1 to n-1).

 If array[j] is smaller than array[minIndex], update minIndex = j.

o Swap array[i] with array[minIndex] if minIndex is not i.

5. Print the sorted array.

6. End.

PSEUDOCODE:::

Function SelectionSort(array, n)

For i = 0 to n-2

minIndex = i

For j = i+1 to n-1

If array[j] < array[minIndex]

minIndex = j

EndIf

EndFor

If minIndex != i

Swap(array[i], array[minIndex])

EndIf

EndFor

EndFunction

Main

Input n

Declare array[n]

For i = 0 to n-1
Input array[i]

EndFor

Call SelectionSort(array, n)

For i = 0 to n-1

Print array[i]

EndFor

EndMain

You might also like