Не правильная последовательность сортировки чисел, как исправить?

При написании курсовой работы столкнулся с неправильным выводом отсортированных елементов, необходимо что б было [1, 2, 3, 4, ...]

На первой фотографии - само начальное диалоговое окновведите сюда описание изображения

после выбора кнопки сортировки, получаем такой результат (например сортировка Шелла)введите сюда описание изображения):

уверен что ошибка скорей всего в этом куске всего проекта IntListModel.cpp

#include "IntListModel.h"

IntListModel::IntListModel(QObject *parent) :
    QAbstractListModel (parent)
{
    for (int i = 0; i < 1000; i++) {
        int t = rand()%1000;
        items << t;
    }
}

int IntListModel::rowCount(const QModelIndex &parent) const
{
    return items.count();
}

QVariant IntListModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid())
    {
        return QVariant();
    }
    if(role == Qt::DisplayRole)
    {
        return items.at(index.row());
    }
    else{
        return QVariant();
    }
}

void IntListModel::sort(int column, Qt::SortOrder order)
{
    if(order == Qt::AscendingOrder)
    {
        std::sort(items.begin(), items.end(), std::less<int>());
    }
    //else {
      //  std::sort(items.begin(), items.end(), std::greate<int>());
//}
}

int SelectionSort(int num[], int numel)
{
    int i, j, min, minidx, grade, moves = 0;

    for (i = 0; i < (numel - 1); i++)

    {

        min = num[i];
        minidx = i;
        for (j = i + 1; j < numel; j++)
        {
            if (num[j] < min)
            {
                min = num[j];
                minidx = j;
            }
        }
        if (min < num[i])
        {
            grade = num[i];
            num[i] = min;
            num[minidx] = grade;
            moves++;
        }
    }

    return moves;
}

int increment(long inc[], long size) {
 int p1, p2, p3, s;

  p1 = p2 = p3 = 1;
  s = -1;
  do {
    if (++s % 2) {
      inc[s] = 8*p1 - 6*p2 + 1;
    } else {
      inc[s] = 9*p1 - 9*p3 + 1;
      p2 *= 2;
      p3 *= 2;
    }
    p1 *= 2;

  } while(3*inc[s] < size);

  return s > 0 ? --s : 0;
}

template<class T>
void shellSort(T a[], long size) {
  long inc, i, j, seq[40];
  int s;
  s = increment(seq, size);
  while (s >= 0) {
    inc = seq[s--];
    for (i = inc; i < size; i++) {
      T temp = a[i];
      for (j = i-inc; (j >= 0) && (a[j] > temp); j -= inc)
        a[j+inc] = a[j];
      a[j+inc] = temp;
    }
  }
}

#include <iterator>

template< typename Iterator >
void adjust_heap( Iterator first
                  , typename std::iterator_traits< Iterator >::difference_type current
                  , typename std::iterator_traits< Iterator >::difference_type size
                  , typename std::iterator_traits< Iterator >::value_type tmp )
{
    typedef typename std::iterator_traits< Iterator >::difference_type diff_t;

    diff_t top = current, next = 2 * current + 2;

    for ( ; next < size; current = next, next = 2 * next + 2 )
    {
        if ( *(first + next) < *(first + next - 1) )
            --next;
        *(first + current) = *(first + next);
    }

    if ( next == size )
        *(first + current) = *(first + size - 1), current = size - 1;

    for ( next = (current - 1) / 2;
          top > current && *(first + next) < tmp;
          current = next, next = (current - 1) / 2 )
    {
        *(first + current) = *(first + next);
    }
    *(first + current) = tmp;
}

template< typename Iterator >
void pop_heap( Iterator first, Iterator last)
{
    typedef typename std::iterator_traits< Iterator >::value_type value_t;

    value_t tmp = *--last;
    *last = *first;
    adjust_heap( first, 0, last - first, tmp );
}

template< typename Iterator >
void heap_sort( Iterator first, Iterator last )
{
    typedef typename std::iterator_traits< Iterator >::difference_type diff_t;
    for ( diff_t current = (last - first) / 2 - 1; current >= 0; --current )
        adjust_heap( first, current, last - first, *(first + current) );

    while ( first < last )
        pop_heap( first, last-- );
}

или же в IntListModel.h

#ifndef INTLISTMODEL_H
#define INTLISTMODEL_H

#include <QAbstractListModel>

class IntListModel : public QAbstractListModel
{
    Q_OBJECT
public:
  explicit IntListModel(QObject *parent = 0);

signals:

public slots:
private:
    QList<int> items;

    // QAbstractItemModel interface
public:
    int rowCount(const QModelIndex &parent) const;
    QVariant data(const QModelIndex &index, int role) const;
    void sort(int column, Qt::SortOrder order);
};

#endif // INTLISTMODEL_H

Будьте добры, помогите, уже себе всю голову поломал, не знаю с чего начать...


Ответы (1 шт):

Автор решения: user394173

На втором скрине числа отсортированы правильно. Не должно быть повторов или что? Если да, то удалите их заранее. Можно сделать и сортировку и удаление добавлением в множество, например.

Если вы хотите именно все числа 0 -> 1000, то используйте просто цикл от 0 до 1000, а не случайные числа, как вы сделали.

Вместо этого

for (int i = 0; i < 1000; i++) {
    int t = rand()%1000;
    items << t;
}

это

for (int i = 0; i < 1000; i++) {
    int t = i;
    items << t;
}

std::random_device rd;
std::mt19937 g(rd());

std::shuffle(items.begin(), items.end(), g);
→ Ссылка