简体   繁体   English

如何优化随机排序算法?

[英]How to optimize random sort algorithm?

Here is some random sort program I wrote in C++. 这是我用C ++编写的一些随机排序程序。 It works pretty fine for 10 elements or so. 对于10个左右的元素,它的效果很好。 But for 15 elements it works so slow I can't even wait enough to get the result. 但是对于15个元素,它是如此缓慢地工作,我什至都等不及要获得结果。 Is there some way to optimize random sort algorithm? 有什么方法可以优化随机排序算法?

Here's my code: 这是我的代码:

// randomsort.h

#ifndef RANDOMSORT_H
#define RANDOMSORT_H

#include <stdlib.h>
#include <time.h>

class RandomSort
{
private:
    template <class T>
    static bool isOrdered(T*, int);

public:
    template <class T>
    static int sort(T*, int);

};

template <class T>
bool RandomSort::isOrdered(T* arr, int size)
{
    for(int i = 1; i < size; i++)
    {
        if(arr[i-1] > arr[i])
        {
            return false;
        }
    }

    return true;
}

template <class T>
int RandomSort::sort(T* arr, int size)
{
    int stepAmount = 0;

    srand(time(NULL));

    while(!isOrdered(arr, size))
    {
        int i = rand() % size;
        int j = rand() % size;

        std::swap(arr[i], arr[j]);

        stepAmount++;
    }

    return stepAmount;
}

#endif // RANDOMSORT_H

And main.cpp file 和main.cpp文件

// main.cpp

#include <iostream>
#include "randomsort.h"

int main()
{
    int size;

    std::cout << "Enter amount of elements to sort: ";
    std::cin >> size;
    std::cout << std::endl;

    int arr[size];

    for(int i = 0; i < size; i++)
    {
        arr[i] = (rand() % (size * 10));
    }

    std::cout << "Input array: " << std::endl;

    for(int i = 0; i < size; i++)
        std::cout << arr[i] << ' ';

    std::cout << std::endl << std::endl;

    int stepAmount = RandomSort::sort(arr, size);

    std::cout << "Output array: " << std::endl;

    for(int i = 0; i < size; i++)
        std::cout << arr[i] << ' ';

    std::cout << std::endl << std::endl;

    std::cout << "Number of steps: " << stepAmount;

    return 0;
}

Any suggestions? 有什么建议么?

Your code is completely random. 您的代码是完全随机的。 So it can swap when it should not. 因此,它可以在不应该交换时进行交换。 An easy fix would be to swap only if you need it. 一个简单的解决方法是仅在需要时才进行交换。

int i = rand() % size;
int j = rand() % size;

// to know which should be first
if (i > j)
  std::swap(i, j);

if (arr[i] > arr[j])
    std::swap(arr[i], arr[j]);

Your array probably will not be sorted immediately, so you could also test if it is sorted only every five steps (for example) instead of every step. 您的数组可能不会立即排序,因此您也可以测试是否仅每5步(例如)而不是每步进行排序。

But i think the most important is, you should not expect good performances from such an algorithm. 但是我认为最重要的是,您不应该期望这种算法具有良好的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM