Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selection Sort from both ends with Min and Max

I was wondering why this code is not outputting the correct sequence of numbers (ascending). It has been taken from this material - Upgraded Selection Sort. For example as I insert in array values like these - [8,5,6,1,4,7,3,0,2,9] it returns - [0,1,3,4,5,7,8,6,2,9].

#include<iostream>
using namespace std;

void Swap(int Arr[100],int Temp_min,int Temp_max)
{
    int temp;
    temp = Arr[Temp_min];
    Arr[Temp_min] = Arr[Temp_max];
    Arr[Temp_max] =temp;
}

void OptimizedSelectSort(int Arr[],int n)
{
    int i,j,min,max;

    for(i=0;i<n/2;i++)
    {
        min = i;
        max = i;
        for(j=i+1;j<n-i;j++)
        {
            if (Arr[j]> Arr[max])
            {
                max = j;
            }
            else if (Arr[j]< Arr[min])
            {
                min = j;
            }
        }
        if (i == max && n-1-i == min)
        {
            Swap(Arr,min,max);
        }
        else
        {
            if ((min == n-1-i) && (max != i))
            {
                Swap(Arr,i,min);
                Swap(Arr,n-1-i,max);
            }
            else if ((max == i) && (min != n-1-i))
            {
                Swap(Arr,n-1-i,max);
                Swap(Arr,i,min);
            }
            else
            {
                if(min != i)
                {
                    Swap(Arr,i,min);
                }
                else if(max!= n-1-i)
                {
                    Swap(Arr,max,n-1-i);
                }
            }
        }
    }
}

int main()
{
    int n;
    cout<<"Enter the size of array"<<endl;
    cin>>n;
    int * Mas;
    Mas = new int [n];
    int i;
    cout<<"Enter the elements"<<endl;
    for(i=0;i<n;i++)
    {
        cin>>Mas[i];
    }
    OptimizedSelectSort(Mas, n);
    cout<<"Sakartots saraksts:";

    for(i=0;i<n;i++)
    {
        cout<<Mas[i]<<" ";
    }
}
like image 256
Pmal12 Avatar asked Nov 09 '22 03:11

Pmal12


1 Answers

There seems to be a typo in the pseudo-code as published in the paper. In the very last part:

else if(max!= n-1-i)

Just remove the else.

That corresponds (better) to the part 5.i and 5.ii of the authors' description of the algorithm.

like image 58
A.S.H Avatar answered Nov 14 '22 21:11

A.S.H