I have this simple implementation for array sorting:
#include <iostream>
#include <stdlib.h>
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 : 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.
std::sort(arr, arr+count);
withstd::sort
from the header<algorithm>
. It works with any container of any comparable value. – Morwenn 17 hours agostd::unique(arr, arr+count)
to get rid of the duplicate elements. – Morwenn 17 hours agoarr[i]
witharr[i+1]
and skip the sequence if equal? Keep trying to do things the hard way, you'll learn more this way. – chqrlie 12 hours agocompare()
can be simplified as:return (a > b) - (a < b);
– chqrlie 12 hours ago