Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

c++ - c + +选择排序在特定情况下不起作用(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.

(在特定情况下,例如,如果我输入想要长度为3的数组,然后将“ 2 1 3”作为输入,它将以相同的顺序输出。)

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 << "
Array after sort: ";
    for(i = 0; i < n; i++){
        cout << nums[i] << ", ";
    }

    return 0;
}

'''

(''')

  ask by macb2001 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Place your swap(nums[min], nums[i]);

(放置您的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]);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...