Selection sort - output problems

Hi, I made a program which sorts (with selection sort) random numbers ascending :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int* SelectionSort(int* a, int n) 
{
    int min;
    for(int i = 0; i < n; i++) 
    {
        min = i;
        for(int j = i + 1; j < n; j++) 
        {
            if(a[j] < a[min]) 
            {
                min = j;
            }
        }
 
        int temp = a[i];
        a[i] = a[min];
        a[min] = temp;
    }
 
    return a;
}


But now I must build syntax in a way that an array which is a parameter of a function (int* a) stayed untouchable (unsorted). I made this :

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
int* SelectionSort(int* a, int n) 
{
    int* new_a = new int[n];
    new_a[0] = a[0];
    int min;
    for(int i = 0; i < n; i++) 
    {
        min = i;
        for(int j = i + 1; j < n; j++) 
        {
            if(a[j] < new_a[min])  // I compare here  
            {
                min = j;
                // here is something missing, I tried a few options but my logic freeze
            }
        }
        
        /* This is not an option, because I can not change a
        int temp = a[i];
        a[i] = a[min];
        a[min] = temp;
        */
    }
 
    return new_a; // return new sorted array


You see I'm stucked in logic how to put sorted numbers in my new array and then return him. I'm sorry for my english I'm still learning. Thanks for all replies.
Made a new array. Copied all values from the old array. Called old working function, which modifies input, on new array. Profit.

You never assign values to new array. Add this to line 17: new_a[i] = a[min];
Last edited on
- Yes, doing what the user above me mentioned should solve your problem.
Sorry I forgot to write this line, because i wrote the code from my head... This still doesn't work :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 int* new_a = new int[n];
    new_a[0] = a[0];
    int min;
    for(int i = 0; i < n; i++) 
    {
        min = i;
        for(int j = i + 1; j < n; j++) 
        {
            if(a[j] < new_a[min])  
            {
                min = j;
            }
        }
        new_a[i] = a[min];
    }
 
    return new_a; 


I tried to sort a numbers : 109, 114, 2 ,1
result : 2,114,2,1
Topic archived. No new replies allowed.