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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…