[英]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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.