0

its not correctly assigning items in an array during the sorting function of selection sort in c++.what is the correct way?

int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 };
int arr_len = sizeof(a)/sizeof(a[0]);

for(int index = 0; index < arr_len - 1; index++)
{
    for(int n = index + 1; n < arr_len; n++)
    {
        if(a[index] > a[n])
        {
            a[index] = a[n];
            a[n] = a[index];
        }
    }
}

the result of my program gave me like this: Array in sorted order: 1 1 1 1 1 1 1 1 1 67

4
  • 1
    a=b followed by b=a will make both a,b = b Commented Sep 6, 2019 at 19:59
  • 1
    Two swap two elements use a "temp" value. temp=a; a=b; b= temp; Commented Sep 6, 2019 at 20:01
  • 1
    or directly std::swap. Commented Sep 6, 2019 at 20:02
  • Unrelated: If t you're compiling to a recent standard, std::size can be used to replace sizeof(a)/sizeof(a[0]) Commented Sep 6, 2019 at 20:57

1 Answer 1

1

Let's say that you want to swap a and b. Let's say that the values are:

a = x
b = y

The first step of your attempt was to assign a = b. After such operation, the situation would be:

a = y
b = y

How could you at this point assign x to b? Think about it.

You can't. The original value of a has been lost. So, clearly this first step leads to a dead end.

The solution: Introduce a new variable, assign a onto that variable, assign b onto a, and finally assign the new variable onto b.

temp = a
a = b
b = temp
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.