选择排序数组
Selection sort array
我试图让我的程序使用选择排序将最小数字排序为最大数字。一切都编译和运行,但是当我尝试使用该程序时,数字的顺序不正确。
您能否查看我的程序,看看是否可以更改任何内容以使其正常运行,因为我尝试了所有方法,但它仍然没有以正确的顺序显示数字。
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void makearray(int data[],int n)
{
for ( int i =0 ; i < n ; i++)
data[i]=(1+rand()%(1000-1+1));
}
template <class item, class sizetype>
int index_of_minimal(const item data[],sizetype i, sizetype n)
{
int index=i;
int first=data[i];
for (i; i < n; i++)
{
if (data[i] < first)
index = i;
}
return index;
}
template <class item, class sizetype>
void swap(item data[],sizetype i, sizetype j)
{
int temp;
temp=data[i];
data[i]=data[j];
data[j]=temp;
}
template <class item, class sizetype>
void selectionsort(item data[], sizetype n)
{
int j;
for(int i=0; i< n-1; i++)
{
j=index_of_minimal(data,i,n);
swap(data,i,j);
}
}
int main()
{
int n;
cout << "Enter n: " ;
cin>>n;
int data[n];
makearray(data,n);
cout << "unsorted array: " ;
for(int i = 0; i < n; i++)
cout << data[i] << " ";
cout << endl;
selectionsort(data, n);
cout << "sorted array: " ;
for(int i = 0; i < n; i++)
cout << data[i] << " ";
cout << endl;
return 0;
}
在index_of_minimal
函数中,您需要重置当前的最小值( first
) 以进行下一次比较,同时保存其索引,否则在迭代中另一个数字,小于原始first
值可能仍然大于您已经处理的值。
所以它应该是这样的:
for (i; i < n; i++)
{
if (data[i] < first)
{
index = i;
first=data[i];//also save the new minimum value
}
}
相关文章:
- 显示错误输出的简单数组排序程序
- C 使用单个函数对具有多种值类型的数组排序
- 2D数组排序,空格打乱顺序
- C 2D数组排序
- C++数组排序 - 将"bbba"和"0001"视为不正确排序的问题
- 数组排序功能
- CString 数组排序
- 简单的数组排序/检查 划分和征服版本
- C++ 中的多维数组排序
- 选择在++中对并行数组排序
- C++:二维指针数组排序:选择排序不适用于某些实例
- C++字符串数组排序
- C++中的指针数组排序算法
- 在VC++6中使用向量进行数组排序时出错,而在VC++2012中没有错误
- 将索引数组排序为主数组
- 数组排序、数组输入、数组输出
- C++数组排序,内存错误
- 在嵌入式系统上将数组排序功能从c++移植到c
- 基于其他int数组排序
- 多维数组排序c++奇怪行为