首页 > 解决方案 > c ++选择排序在特定情况下不起作用

问题描述

我创建了一个程序,它使用选择排序对数组中的整数进行排序。在特定情况下,例如如果我输入我想要一个长度为 3 的数组,然后将“2 1 3”作为我的输入,它会以相同的顺序输出它。它适用于其他输入,但由于某种原因,它时不时地无法正确排序整数列表。我的代码如下:'''

#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;
}

'''

标签: c++sorting

解决方案


将您的swap(nums[min], nums[i]);语句放在内部循环之外,就像这样

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]);
    }
}

推荐阅读