Files
sort-and-png/sort/main.cpp
2018-05-31 21:59:36 +08:00

141 lines
2.7 KiB
C++

#include <random>
#include <functional>
#include <iostream>
using namespace std;
#define CONT
#define COUT
struct LinkNode{
int data;
LinkNode* next;
};
#ifdef CONT
long int cont_if = 0;
long int cont_change = 0;
#endif
#ifdef CONT
void coutList(LinkNode* head){
head = head->next;
while (head){
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
#endif
LinkNode* initArandList(int num){
auto* head = new LinkNode{0, nullptr};
default_random_engine generator;
uniform_int_distribution<int> dis(0,10000);
auto dice = bind(dis,generator);
for(int i=0;i<num;i++)
head = new LinkNode{dice(),head};
return head;
}
void InsertSort(LinkNode* in) {
#ifdef CONT
cont_if = 0;
cont_change = 0;
#endif
LinkNode *h1 = nullptr, *h2 = nullptr, *h3 = nullptr;
h3 = in;
h2 = in->next;
while (h2) {
h1 = in;
#ifdef CONT
cont_change += 1;
#endif
while (h1 != h2) {
#ifdef CONT
cont_if++;
#endif
if (h1->next->data < h2->data) {
h3->next = h2->next;
h2->next = h1->next;
h1->next = h2;
h2 = h3->next;
#ifdef CONT
cont_change += 4;
#endif
#ifdef COUT
coutList(in);
#endif
break;
}
h1 = h1->next;
#ifdef CONT
cont_change += 1;
#endif
}
if (h1 == h2) {
h2 = h2->next;
h3 = h3->next;
#ifdef CONT
cont_change += 2;
#endif
}
}
}
void BubbleSort(LinkNode* in){
#ifdef CONT
cont_if = 0;
cont_change = 0;
#endif
LinkNode *end= nullptr,*head;
int tmp = 0;
while(end != in->next){
head= in->next;
while (head->next != end){
if(head->data > head->next->data){
#ifdef CONT
cont_if++;
cont_change +=3;
#endif
tmp = head->data;
head->data = head->next->data;
head->next->data = tmp;
#ifdef COUT
coutList(in);
#endif
}
head = head->next;
#ifdef CONT
cont_change +=1;
#endif
}
end = head;
#ifdef CONT
cont_change +=2;
#endif
}
}
void SelectionSort(LinkNode *in){
#ifdef CONT
cont_if = 0;
cont_change = 0;
#endif
LinkNode *end=in,*head=end,*beformin = nullptr,*tmp;
while (end){
beformin = end;
while (head->next){
if(head->next->data < beformin->next->data){
beformin = head;
}
head = head->next;
}
tmp = beformin->next;
beformin->next = tmp->next;
tmp->next = end->next;
end->next = tmp;
end = tmp;
}
}
int main()
{
}