﻿ 随机打乱给定数组 Randomize Algorithm - 鸿网互联

# 随机打乱给定数组 Randomize Algorithm

```#include "HornersRuleTest.h"
#include "PermutationTest.h"
#include "HanoiTower.h"
#include <iostream>

using namespace std;

int main()
{
//hornersRule();
//permutationTest();
//runMove();
vector<double> data = { 1.0, 2.4, 3, 3.5, 4.2, 5.5, 6.8 };
Randomize<double> randomize(data);
data = randomize.getRandomizedData();
printf("New data: ");
for (int index = 0; index < data.size(); index++)
printf("%f ", data.at(index));
printf("\n");
system("Pause");
return 0;
}```
```#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<time.h>
#include<cmath>
#include "HeapSort.h"

using namespace std;

template <typename E>
class Randomize
{
public:
Randomize(vector<E> data)
{
datalist = data;
srand(time(NULL));
for (int index = 0; index < datalist.size(); index++)
{
int val = (int)(rand() * 1.0 / RAND_MAX * (pow(datalist.size(), 3) - 1) + 1);
Event newEvent;
newEvent.priority = val;
newEvent.data = datalist.at(index);
eventlist.push_back(newEvent);
}//end loop

int * priorityList = new int[datalist.size()];
printf("Priority: ");
for (int index = 0; index < datalist.size(); index++)
{
priorityList[index] = (eventlist.at(index).priority);
printf("%d ", priorityList[index]);
}
printf("\nData: ");
for (int index = 0; index < eventlist.size(); index++)
{
printf("%f ", eventlist.at(index).data);
}
printf("\n\n");

heapSort(priorityList, datalist.size());

for (int index = 0; index < eventlist.size(); index++)
{
if (eventlist.at(index).priority != priorityList[index])
{
Event temp = eventlist.at(index);
for (int j = index; j < eventlist.size(); j++)
{
if (eventlist.at(j).priority == priorityList[index])
{
eventlist.at(index) = eventlist.at(j);
eventlist.at(j) = temp;
break;
}
}//end loop
}//end if
}//end loop

printf("Priority: ");
for (int index = 0; index < datalist.size(); index++)
printf("%d ", eventlist.at(index).priority);
printf("\nData: ");
for (int index = 0; index < eventlist.size(); index++)
{
datalist.at(index) = eventlist.at(index).data;
printf("%f ", eventlist.at(index).data);
}
printf("\n");

}//end constructor

vector<E> getRandomizedData()
{
return datalist;
}

private:
struct Event
{
int priority;
E data;
}newEvent;
vector<Event> eventlist;
vector<E> datalist;
};//end class.```

<