HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Array Sorting in C++

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraysortingstackoverflow

Problem

I have this simple implementation for array sorting:

#include 
#include 

using namespace std;

// some magic for the sorter
int compare(const void *i, const void *j) {
    int a = *(int *) i, b = *(int *) j;
    return a  b ? 1 : 0;
}

int main() {
    int arr[100], temp = 0, count = 0;

    // reads values into the array (assumed integers as input)
    while (cin >> arr[count++]);
    count--;

    // what sorts the array
    qsort(arr, count, sizeof(int), compare);

    // prints everything but duplicate elements
    for (int i = 0; i < count; i++) {
        bool match = false;
        for (int j = 0; j < i && !match; j++)
            if (arr[i] == arr[j])
                match = true;
        if (!match)
            cout << arr[i];
    }
}


How can it be improved? I'd like to also remove duplicate elements rather than just silently ignoring them too.

Solution

You should use your standard libraries when you can. Consider that a std::set already does all the hard work, unique, and sorted values:

#include 
#include 

int main() {
    std::set data;

    // reads values into the set (assumed integers as input)
    int val;
    while (std::cin >> val) {
        data.insert(val);
    }

    for(std::set::iterator iter = data.begin(); iter != data.end(); ++iter) {
        std::cout << (*iter) << "\n";
    }

}


Note though, that the above implementation has horrible handling of issues that may come from invalid input. Still, the entire implementation is significantly simpler than yours.

Code Snippets

#include <iostream>
#include <set>

int main() {
    std::set<int> data;

    // reads values into the set (assumed integers as input)
    int val;
    while (std::cin >> val) {
        data.insert(val);
    }

    for(std::set<int>::iterator iter = data.begin(); iter != data.end(); ++iter) {
        std::cout << (*iter) << "\n";
    }

}

Context

StackExchange Code Review Q#84994, answer score: 8

Revisions (0)

No revisions yet.