简体   繁体   中英

How to optimize random sort algorithm?

Here is some random sort program I wrote in C++. It works pretty fine for 10 elements or so. But for 15 elements it works so slow I can't even wait enough to get the result. 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

#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.

But i think the most important is, you should not expect good performances from such an algorithm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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