larman
larman

Reputation: 45

Selection sort array

I was trying to make my program sort the smallest number to the largest using selection sort. Everything compiles and runs, but the numbers are not in the right order when i try to use the program.

Can you look over my program to see if there is anything i can change to make it run correctly, because i tried everything and its still not showing the numbers in the right order.

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

void makearray(int data[],int n)
{
for ( int i =0 ; i < n ; i++)
    data[i]=(1+rand()%(1000-1+1));
}


template <class item, class sizetype>
int index_of_minimal(const item data[],sizetype i, sizetype n)
{
    int index=i;
    int first=data[i];

    for (i; i < n; i++)
    {
        if (data[i] < first)
            index = i;
    }

    return index;
}


template <class item, class sizetype>
void swap(item data[],sizetype i, sizetype j)
{
    int temp;

    temp=data[i];
    data[i]=data[j];
    data[j]=temp;
}


template <class item, class sizetype>
void selectionsort(item data[], sizetype n)
{
    int j;
    for(int i=0; i< n-1; i++)
    {
        j=index_of_minimal(data,i,n);
        swap(data,i,j);
    }

}

int main()
{
    int n;

    cout << "Enter n: " ;
    cin>>n;
    int data[n];
    makearray(data,n);

    cout << "unsorted array: " ;
    for(int i = 0; i < n; i++)
        cout << data[i] << " ";
    cout << endl;

    selectionsort(data, n);

    cout << "sorted array: " ;
    for(int i = 0; i < n; i++)
        cout << data[i] << " ";
    cout << endl;
    return 0;
}

Upvotes: 0

Views: 351

Answers (1)

Biruk Abebe
Biruk Abebe

Reputation: 2233

In your index_of_minimal function, you need to reset the current smallest value(first) for the next comparison along with saving its index, otherwise another number, in your iteration, less that the original first value may still be larger than the ones you've already processed.

So it should be like this:

for (i; i < n; i++)
{
    if (data[i] < first)
    {
        index = i;
        first=data[i];//also save the new minimum value
    }
}

Upvotes: 1

Related Questions