hello i need a help in a recursion

i need to place the minimum number in the inition of the sorted array (i did it) and then to sort other by size .please help me in the first function ..where is the mistake?

thanks a lot


#include <iostream>
#include <stdlib.h>

using namespace std;

#define SIZE 10

int index_of_min(int arr2[ ], int start, int end)

{
if (start == end) //condition for stopping the function and returning the start

return start;

if( arr2[start] < arr2[end] )

return index_of_min( arr2, start, end-1 );

return index_of_min( arr2, start+1, end );
}


void selection_sort (int arr[ ], int start, int end)//that function will find the minimum in the array
{
int tmp = arr[0];//swaping

arr[0] = arr[index_of_min(arr,0,9)];

arr[index_of_min(arr,0,9)] = tmp;

}


void main()
{
int array[SIZE];

cout<<"The initial array is: ";

for (int i=0; i<SIZE; i++)
{
array[i] = rand() % 100;

cout<<array[i]<<" ";

}

cout<<endl;

selection_sort(array,0,11);

cout<<"The sorted array is: ";
for(int i=0 ; i<SIZE;i++)

cout<<array[i]<<" ";

cout<<endl;

}


Several points here.

The call to function selection_sort() should use the defined constant SIZE rather than some particular number.

The function selection_sort receives input parameters start and end, but ignores them and instead uses hard-coded values of 0 and 9.

The swapping operation calls function index_of_min twice which is inefficient, and potentially error-prone, since the array has been modified before the second call.

And finally, selection_sort needs to call itself recursively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <cstdlib>
#include <iomanip>

using namespace std;

#define SIZE 10

int index_of_min(int arr2[ ], int start, int end)
{
    if (start == end)
        return start;

    if ( arr2[start] < arr2[end] )
        return index_of_min( arr2, start, end-1 );

    return index_of_min( arr2, start+1, end );
}

void selection_sort (int arr[ ], int start, int end)
{
    if (start == end)
        return;

    int indexmin = index_of_min(arr,start,end);

    // Swap elements
    int tmp       = arr[start];
    arr[start]    = arr[indexmin];
    arr[indexmin] = tmp;

    // recursive call
    selection_sort (arr, start+1, end);
}

int main()
{
    srand(time(0));  // Optional seeding of random number generator

    int array[SIZE];

    cout<<"The initial array is: ";

    for (int i=0; i<SIZE; i++)
    {
        array[i] = rand() % 100;
        cout << setw(2) << array[i] << " ";
    }

    cout<<endl;

    selection_sort(array,0,SIZE-1);

    cout<<"The sorted array is:  ";

    for (int i=0 ; i<SIZE; i++)
        cout << setw(2) << array[i] << " ";

    cout<<endl;

    return 0;
}
thank you a lot!!
Topic archived. No new replies allowed.