Shell Sorting a doubly linked list
Dec 17, 2014 at 2:40pm UTC
I got this project to create a doubly linked list from a file and sort it via the Shell sorting method. I think I figure it out (the logic behind the algorithm and how it works), and it really does sort the numbers I'm putting in the list without any errors, but I really need to be sure if I did it right. The function that I'm concerned about is ShellSort(). So here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
using namespace std;
const int N=10;
struct node
{
int data;
node* next;
node* prev;
}
*head = NULL;
void addNode(int x)
{
node *p=head, *q;
q=new node;
q->data=x;
q->next=NULL;
if (head)
{
while (p->next)
p=p->next;
p->next=q;
}
else
head=q;
q->prev=p;
}
int CreateFile ()
{
int num[N];
ofstream file1;
file1.open("Numbers1.txt" );
if (file1.fail())
{
cout<<"Error opening the file" <<endl;
return 1;
}
cout<<"Enter 10 numbers (will be stored to a file): " <<endl;
for (int i=0;i<N;i++)
{
cin>>num[i];
file1<<num[i]<<endl;
}
cout<<endl;
cout<<"The numbers were succsessfully stored to a text file (Numbers1.txt)" <<endl;
file1.close();
return 0;
}
void CreateListFromFile()
{
int b=0;
ifstream file2;
file2.open("Numbers1.txt" );
if (file2.is_open())
{
while (file2>>b)
{
addNode(b);
}
}
file2.close();
}
void ShowList(node *head)
{
node *temp = head;
while (temp != NULL)
{
cout<< temp->data<<" " ;
temp = temp->next;
}
cout<<endl;
}
void ShellSort()
{
if (head)
{
int step=0;
int lenght=0;
node *p=head;
while (p)
{
lenght++;
p=p->next;
}
while (2*(3*step+1)<=lenght)
step=3*step+1;
for (step;step>0;step/=3)
for (int i=step;i>0;i--)
for (int j=step-i; j<lenght; j+=step)
{
p=head;
int k;
for (k=0;k<j;k++)
p=p->next;
node* c=p;
int temp=k+step;
while (c)
{
for (k;k<temp;)
if (c)
{
k++;
c=c->next;
}
else break ;
if (c)
if (p->data>c->data)
{
int t=p->data;
p->data=c->data;
c->data=t;
}
temp+=step;
}
}
}
cout<<"Sorting is done" <<endl;
}
void main()
{
CreateFile();
CreateListFromFile();
ShellSort();
ShowList(head);
}
Dec 18, 2014 at 1:21pm UTC
bump ...
Jan 5, 2015 at 3:44pm UTC
Still waiting for backup.
Topic archived. No new replies allowed.