user2999132
user2999132

Reputation:

Array sorting backwards?

Okay so I have this function that takes an array and sorts it by using swap sort(?) however when I enter the numbers it sorts it from largest to smallest instead of smallest to largest.

I went through and did this to see what happens each step of the way however it all seems correct to me.

iterator = &first element
temp = smallest number
tempstore = &smallest number
val tempstore = val first element
val first element = val temp

If i change it so that

if(array[i] < *iterator)

becomes:

 if(array[i] > *iterator)

it works perfectly but I don't understand this as now it is testing to see if the number is larger and I want smaller.

I know I should probably be using a vector but I am still a newbie and I am yet to learn them. Thanks for any help.

int *sort(int *array, int size)
{
    int temp, *iterator, *tempStore;
    for(int j = 0; j < size; j++)
    {
        iterator = &array[j];
        for(int i = 0; i < size; i++)
        {
            if(array[i] < *iterator)
            {
                temp = array[i];
                tempStore = &array[i];
                *tempStore = *iterator;
                *iterator = temp;
            }
        }
    }
    return array;
}

Upvotes: 0

Views: 224

Answers (1)

DarioP
DarioP

Reputation: 5465

Your algorithm compares the first element of the array with all the subsequent, so when you use:

 if(array[i] > *iterator)

you swap the first element with the ith element every time the ith element is greater than the first. So at the end of the first pass you have the greatest element in the first position. if you use the < operator, you get the smallest in front.

Then the second pass should compare the second element of the array with all the subsequent and so on, that's why i needs to start iterating from j + 1.

As you saw it is not straightforward to read and understand the code, moreover the algorithm itself is very poor (it looks like a selection sort with some extra swaps). You do not necessarily need to use a std::vector but you really should learn the standard library.

This is the C++11 way to do it:

#include <algorithm> //for std::sort
#include <iterator> //for std::begin/end
#include <functional> //for std::greater

int v[1000];
... fill v somehow ...
std::sort(std::begin(v), std::end(v), std::greater<int>());

Compact, clear and extremely fast.

Upvotes: 1

Related Questions