I have an assignment that I have been stuck on, and unable to figure out after quite a bit of research.
I need to sort an array of size 20 with values between 1 and 101, using a function that returns the smallest value in the array.
Here is my function that returns the smallest value in the array.
int problem5(int *arr, int size, int &m, int &n){//Definition Problem 5
int smallest = 101;
int smallestindex;
for ( int i=0; i < size; ++i ){
if ( arr[i] < smallest ){
smallest = arr[i];
smallestindex = i;
}
}
m=smallest;
n=smallestindex;
cout<<"Smallest value is "<<m<<endl;
cout<<"It's index is "<<n<<endl;
return n;
}`
And here is my function, I am trying to switch the index of the first value in the array with the index of the smallest value, then have the array not include the first value(smallest value) in the new array. Here is that code:
void problem8(int *x, int size){
int m = 101;
int n = 101;
int tmpsize = size;
problem4(x,20);
for(int i =0; i<size; i++){
swap(x[i],x[problem5(&x[i],tmpsize, m, n)]);
tmpsize = tmpsize - 1;
}
}`
For the first few loops it will not change the array, but will correctly identify the smallest value. Thank you in advance for the help.
答案 0 :(得分:0)
problem5(&x[i], tmpsize, m, n);
swap(x[i], x[n]);
应该是
n
目前您可能已超出限制访问权限。
我建议您将m
中的变量problem8
,smallIndex
重命名为smallestValue
,int find_min(const int* arr, int size, int& value, int& index)
{
int smallest = 101;
int smallestindex;
for (int i = 0; i < size; ++i) {
if (arr[i] < smallest) {
smallest = arr[i];
smallestindex = i;
}
}
value = smallest;
index = smallestindex;
return n;
}
int problem5(int* arr, int size, int& m, int& n)
{
int res = find_min(arr, size, m, n)
std::cout << "Smallest value is "<< m << std::endl;
std::cout << "It's index is " << n << std::endl;
return res;
}
void selection_sort(int* x, int size)
{
int value = 101;
int index = 101;
int tmpsize = size;
for(int i = 0; i<size; i++) {
problem5(&x[i], tmpsize, value, index);
swap(x[i], x[index]);
tmpsize = tmpsize - 1;
}
}
void problem8(int* x, int size){
problem4(x, 20); // better name ?
selection_sort(x, size);
}
。结果如下:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button7.Click
Dim BT As Button = CType(sender, Button)
Select Case BT.Name
Case Button1.Name
form1.Show
Panel2.Hide()
Case Button2.Name
...whatever
Case Button7.Name
...whatever
End Select
End Sub