macb2001
macb2001

Reputation: 11

c++ Selection sort isn't working in specific cases

I've created a program that uses selection sort to sort integers in an array. In specific cases, such as if I input that I want an array of length 3 and then have "2 1 3" as my input, it outputs it in the same order. It's working for other inputs, but every now and then for some reason it wont sort a list of integers correctly. My code is as follows: '''

#include <iostream>
using namespace std;

void sort(int[], int);
void swap(int&, int&);

void swap(int &a, int &b){
    int temp;
    temp = a;
    a = b;
    b = temp;
}

void sort(int nums[], int n){
    int j, min, i;
    for (i = 0; i < n - 1; i++){
        min = i;
        for(j = i + 1; j < n; j++){
            if(nums[j] < nums[min]){
                min = j;
            }
        swap(nums[min], nums[i]);

        }
    }
}

int main(){
    int n, i;
    cout << "Enter how many numbers you want to sort" << endl;
    cin >> n;
    int nums[n];

    cout << "Enter the integers seperated by a space: ";

    for(i = 0; i < n; i++){
        cin >> nums[i];
    }

    cout << "Array Before Sort: ";
    for (i = 0; i < n; i++){
        cout << nums[i] << ", ";
    }

    sort(nums, n);

    cout << "\nArray after sort: ";
    for(i = 0; i < n; i++){
        cout << nums[i] << ", ";
    }

    return 0;
}

'''

Upvotes: 1

Views: 73

Answers (1)

Ajay Dabas
Ajay Dabas

Reputation: 1444

Place your swap(nums[min], nums[i]); statement outside of inner loop, like this

void sort(int nums[], int n){
    int j, min, i;
    for (i = 0; i < n - 1; i++){
        min = i;
        for(j = i + 1; j < n; j++){
            if(nums[j] < nums[min]){
                min = j;
            }
        }
        swap(nums[min], nums[i]);
    }
}

Upvotes: 1

Related Questions