c++ - 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;
}
'''
解决方案
将您的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]);
}
}
推荐阅读
- sql - 基于行划分,没有多个查询
- java - Vaadin Spring Boot 找不到 npm 包
- python-3.x - Python中是否有用于多元数据分析的功能
- c# - 有没有办法在 DuplexChannelFactory<> 中有多个回调?
- flutter - Flutter 应用程序,Theme.of(context) 样式不适用于文本
- c# - 如何使自定义 ModelBinder 自动应用于某种类型的所有属性
- reactjs - 无法在反应项目中使用recordRTC
- twilio - 如何在 Twilio 视频室中检测按键音 (DTMF)
- oracle - Oracle 手册失败——使用“Accessible By”子句的包演示抛出异常
- c++ - 项目中类的 C++ 未解决的外部问题