samedi 25 juillet 2020

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

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

Aucun commentaire:

Enregistrer un commentaire