# C++ Selection Sort not Sorting Some Values of an Array

Stack Overflow Asked by Steffen Brown on January 3, 2022

I am trying to sort an array of integers using a selection sort algorithm, but some of the numbers aren’t sorting. Below is the isolated section of my code that does the sorting and the output. Any suggestions?

#include <iostream>

using namespace std;

int main()
{
int smallestIndex;
int temp;

int X[13] = {1, 19, 2, 18, 4, 12, 7, 8, 10, 3, 11, 17, 9};

for (int Index = 0; Index < 12; Index++) {
smallestIndex = Index;
for (int minIndex = Index+1; minIndex < 13; minIndex++) {
if (X[minIndex] < X[smallestIndex]) {
smallestIndex=minIndex;
}
if (smallestIndex != Index) {
temp = X[Index];
X[Index] = X[smallestIndex];
X[smallestIndex] = temp;
}
}
}

for (int i = 0; i < 13; i++) {
cout << X[i] << endl;
}
}


output:

1
2
4
7
9
3
10
8
11
12
17
18
19


There is an easier way to do this by using the swap() function, and using two more functions called, void selectionSort() and void printArray() to make the code look cleaner.

#include <iostream>
#include <algorithm>

void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)
{
int i, j, min_idx;

// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

swap(&arr[min_idx], &arr[i]);
}
}

void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
}

int main()
{
int arr[] = {1, 19, 2, 18, 4, 12, 7, 8, 10, 3, 11, 17, 9};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
std::cout << "The sorted array is: n";
printArray(arr, n);
return 0;
}


Output:

The sorted array is:
1 2 3 4 7 8 9 10 11 12 17 18 19


Another way you could do this is by just strictly using std::swap without the use of pointers. Make sure to include the #include<algorithm> header file for std::swap. You will also need to include #include <iterator> for std::size.

#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
int arr[] = {1, 19, 2, 18, 4, 12, 7, 8, 10, 3, 11, 17, 9};
constexpr int length{ static_cast<int>(std::size(arr)) };
//constexpr means that value of a variable can appear in a constant expression.

// Step through each element of the array

for (int startIndex{ 0 }; startIndex < length - 1; ++startIndex)
{

int smallestIndex{ startIndex };

// Then look for a smaller element in the rest of the array
for (int currentIndex{ startIndex + 1 }; currentIndex < length; ++currentIndex)
{
if (arr[currentIndex] < arr[smallestIndex])

smallestIndex = currentIndex;
}

// swap our start element with our smallest element
std::swap(arr[startIndex], arr[smallestIndex]);
}

// Now that the whole array is sorted, print it.
for (int index{ 0 }; index < length; ++index)
std::cout << arr[index] << ' ';

std::cout << 'n';

return 0;
}


You could also just use std::sort instead. It is in the header file #include<algorithm> which just sorts in ascending order by default. You will also need the header file #include <iterator> for std::size

#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
int arr[] = {1, 19, 2, 18, 4, 12, 7, 8, 10, 3, 11, 17, 9};

std::sort(std::begin(arr), std::end(arr));

for (int i{ 0 }; i < static_cast<int>(std::size(arr)); ++i)
std::cout << array[i] << ' ';

std::cout << 'n';

return 0;
}


Answered by Geno C on January 3, 2022

## Related Questions

### How to use the “clockwise/spiral rule” to read a const class member function?

1  Asked on December 13, 2020 by ivanagyro

### Amplify Hosted web-UI sign-in / sign-up call throws error randomly

0  Asked on December 13, 2020 by mashhood-riaz

4  Asked on December 12, 2020 by ameena

### How to configure MySQL 8.0.21 to use databases from 8.0.18 on macOS 10.14

0  Asked on December 12, 2020 by julius-patta

### Getting date for calculation

1  Asked on December 12, 2020 by faizan-gauhar

### Map bash table output to array

1  Asked on December 12, 2020 by jeroen-smink

### I get these erros whenever I try to access User Accounts my phpmyadmin

0  Asked on December 12, 2020 by celso-mauro

### Multiple conditions in SELECT Statement

1  Asked on December 12, 2020 by rick-smith

### Set up different CORS rules based on the endpoint in Django

2  Asked on December 12, 2020 by augusto-samam-barrientos

### How to customize sleuth span in spring reactor?

0  Asked on December 12, 2020 by voipp

### Angular check and uncheck boxes from data

1  Asked on December 12, 2020 by mg91

### What should I add to print all the questions I have passed in the driver class?

2  Asked on December 12, 2020 by suvab

### how do i switch a condition based on bind variable

1  Asked on December 12, 2020 by vivek

### Comparing two triangles in C (3, 3, 4 and 4, 3, 3 for example)

3  Asked on December 12, 2020 by etoile

### Grouping unique values with low value counts

1  Asked on December 12, 2020 by yupper

### RealityKit: Entity convert() result switching back and forth between frames

0  Asked on December 12, 2020 by vfxdev

### Why should I press ENTER before CTRL+D to indicate an EOF to stdin?

1  Asked on December 11, 2020 by name-null

### Return matching value from substring in a list against dictionary containing substring

1  Asked on December 11, 2020 by jajao555