Data structure review: C ++ implementation of several sort algorithms and implementation of related Binary Tree Algorithms

Source: Internet
Author: User

The data definition of a binary tree is realized in C language. The construction and destruction of a binary tree, as well as the recursive algorithms of the first, middle, and back orders are being studied.

/* Optional /*--------------------------------------------------------------------------------------------*/

// The binary tree binary linked list storage structure is implemented in C language.

// Implement recursion of the first, middle, and last Traversal Algorithms by creating a binary tree using the first ordinal Sequence

// Non-recursive algorithms.

// Version: V1.0

// Environment: Visual C ++ 6.0

// Author: sunnyrain

// Date: 2007-8-24

/* Optional /*--------------------------------------------------------------------------------------------*/

// Bitree. h

Struct bitnode // uses the binary linked list Storage Structure
{
Char data;
Struct bitnode * lchild;
Struct bitnode * rchild;
} Bitnode;

Struct bitnode * createbitree ();
Int destroybitree (struct bitnode * t );
Int visit (char ELEM );

// Recursive Traversal Algorithm
Int preordertraverse_r (struct bitnode * t, INT (* visit) (char ELEM ));
Int inordertraverse_r (struct bitnode * t, INT (* visit) (char ELEM ));
Int postordertraverse_r (struct bitnode * t, INT (* visit) (char ELEM ));

// Non-recursive Traversal Algorithm
Void preordertraverse (struct bitnode * t, INT (* visit) (char ELEM ));
Void inordertraverse (struct bitnode * t, INT (* visit) (char ELEM ));
Void postordertraverse (struct bitnode * t, INT (* visit) (char ELEM ));

// Stack. h stack data structure, used for additional space in non-Recursive Algorithms

# Define stack_size 256

Struct Stack
{
Struct bitnode * ELEM [stack_size];
Int top; // top always points to the previous element on the top of the stack.
Int bottom; // constant 0
};
Void initstack (struct stack * s );
Struct bitnode * gettop (struct stack * s );
Struct bitnode * Pop (struct stack * s );
Void push (struct stack * s, struct bitnode * P );
Int isempty (struct stack * s );

// Stack. c stack implementation

# Include <stdio. h>
# Include <string. h>
# Include "Stack. H"

// The initialization stack is 0, and the stack pointer is 0.
Void initstack (struct stack * s)
{
Memset (S-> ELEM, 0, stack_size );
S-> Top = s-> bottom = 0;
}

// Obtain the top element of the stack, and the top pointer of the stack remains unchanged.
Struct bitnode * gettop (struct stack * s)
{
Return S-> ELEM [S-> top-1];
}

// Pop up & return the top element of the stack
Struct bitnode * Pop (struct stack * s)
{
If (S-> Top = s-> bottom) // If the stack is empty
{
Printf ("Stack is empty! /N ");
Return 0;
}

-- S-> top;
Return S-> ELEM [S-> top];
}

// Press the Pb pointer into the stack
Void push (struct stack * s, struct bitnode * pb)
{
If (S-> top <stack_size) // the stack is not full.
{
S-> ELEM [S-> top] = Pb;
+ + S-> top;
}
Else
Printf ("Stack is full! /N ");
}

// Judge whether the stack is empty. If it is null, no value is returned.
Int isempty (struct stack * s)
{
Return S-> Top = s-> bottom;
}
// Bitree. c Binary Tree creation, destruction, and recursive algorithm implementation

# Include <stdio. h>
# Include <malloc. h>
# Include "bitree. H"
# Include "Stack. H"

Struct bitnode * createbitree () // create a binary tree using the first-order recursive method
{
Struct bitnode * t;
Char CH, TMP;
Printf ("Please input the value of the node:/N ");
Scanf ("% C", & Ch );
TMP = getchar (); // ignore carriage return
If (CH = '&') // enter & symbol to indicate that this node is empty
{
Printf ("null bitreenode created! /N ");
T = NULL;
Return NULL;
}
 
T = (struct bitnode *) malloc (sizeof (bitnode); // allocate memory for the current node
If (! T)
{
Printf ("allocate memory failed! /N ");
Return NULL;
}

T-> DATA = CH; // assign values to the current node

T-> lchild = createbitree (); // recursively create the left subtree
T-> rchild = createbitree (); // recursively create the right subtree

Return T;
}

// If the binary tree is destroyed, 0 is returned for successful destruction and 1 is returned for error.
Int destroybitree (struct bitnode * t)
{
If (t)
{
Struct bitnode * lchild = T-> lchild;
Struct bitnode * rchild = T-> rchild;
Free (t );
If (0 = destroybitree (lchild ))
{
If (0 = destroybitree (rchild ))
Return 0;
Else
Return 1;
}
}
Return 0;
}
// Access Node Element
Int visit (char ELEM)
{
If (ELEM = '&')
Return 1;
Printf ("% C", ELEM );
Return 0;
}

// First traverse the recursive algorithm. If the returned value is 0, the traversal is successful, and 1 is failed.
Int preordertraverse_r (struct bitnode * t, INT (* visit) (char ELEM ))
{
If (t)
{
If (0! = Visit (t-> data) // access the root node
Return 1;

If (t-> lchild)
{
If (0! = Inordertraverse_r (t-> lchild, visit) // recursively traverse the left subtree
Return 1;
}

If (t-> rchild)
{
If (0! = Inordertraverse_r (t-> rchild, visit) // recursively traverse the right subtree
Return 1;
}
}
Return 0;
}

// Recursive Traversal Algorithm in the middle order. If the returned value is 0, the traversal is successful, and 1 is failed.
Int inordertraverse_r (struct bitnode * t, INT (* visit) (char ELEM ))
{
If (t)
{
If (t-> lchild)
{
If (0! = Inordertraverse_r (t-> lchild, visit) // recursively traverse the left subtree
Return 1;
}

If (0! = Visit (t-> data) // access the root node
Return 1;

If (t-> rchild)
{
If (0! = Inordertraverse_r (t-> rchild, visit) // recursively traverse the right subtree
Return 1;
}
}
Return 0;
}

// Recursive algorithm for post-order traversal. If 0 is returned, the traversal is successful. If 1 is failed.
Int postordertraverse_r (struct bitnode * t, INT (* visit) (char ELEM ))
{
If (t)
{
If (t-> lchild)
{
If (0! = Postordertraverse_r (t-> lchild, visit) // recursively traverses the left subtree
Return 1;
}

If (t-> rchild)
{
If (0! = Postordertraverse_r (t-> rchild, visit) // recursively traverses the right subtree
Return 1;
}

If (0! = Visit (t-> data) // access the root node
Return 1;
}
Return 0;
}

// First traverse non-Recursive Algorithms
Void preordertraverse (struct bitnode * t, INT (* visit) (char ELEM ))
{
Struct stack SS;
Struct bitnode * P = T;
Initstack (& SS );
While (p |! Isempty (& SS ))
{
If (P)
{
Visit (p-> data );
Push (& SS, P );
P = p-> lchild;
}
Else
{
P = gettop (& SS );
Pop (& SS );
P = p-> rchild;
}
}
}

// Non-recursive algorithm for sequential Traversal
Void inordertraverse (struct bitnode * t, INT (* visit) (char ELEM ))
{
Struct stack SS;
Struct bitnode * P;
Initstack (& SS );

Push (& SS, t );
While (! Isempty (& SS ))
{
While (P = gettop (& SS ))
Push (& SS, p-> lchild); // to the left to the end
P = POP (& SS); // empty pointer rollback

If (! Isempty (& SS ))
{
P = POP (& SS );
Visit (p-> data); // access the node
Push (& SS, p-> rchild); // one step to the right
}
}
}

// Post-order traversal of non-Recursive Algorithms
Void postordertraverse (struct bitnode * t, INT (* visit) (char ELEM ))
{
Struct stack SS;
Struct bitnode * P = T;
Struct bitnode * q;
Initstack (& SS); // Initialize an empty Stack

While (p |! Isempty (& SS ))
{
If (P)
{
Push (& SS, P );
P = p-> lchild;
}
Else
{
P = gettop (& SS );
If (P)
{
Push (& SS, null );
P = p-> rchild;
}
Else
{
Pop (& SS );
Q = POP (& SS );
Visit (Q-> data );
}
}
}
}

 

// Main. C test the main program

# Include <stdio. h>
# Include "bitree. H"

Int main ()
{
Struct bitnode * bt = 0;
Bt = createbitree (BT );
Printf ("first-order traversal sequence:/N ");
Preordertraverse_r (BT, visit );
Printf ("/n ordinal traversal sequence:/N ");
Inordertraverse_r (BT, visit );
Printf ("/n post-order traversal sequence:/N ");
Postordertraverse_r (BT, visit );

Printf ("/N non-recursive first-order traversal sequence:/N ");
Preordertraverse (BT, visit );

Printf ("/N non-recursive sequential traversal sequence:/N ");
Inordertraverse (BT, visit );

Printf ("/N non-recursive post-sequential traversal sequence:/N ");
Postordertraverse (BT, visit );
Destroybitree (BT );
Return 0;
}

 

 

 

 

According to the algorithm in the book, the algorithm in the book uses the array 0 subscript element as the sentry, considering that when the input array cannot leave a sentry location, it is rewritten a little, insert sorting can begin with 0 subscript.

/* ===================================================== ========================================================== =

Function: directly insert and sort the array of elements that can be compared with <.

Author: sunnyrain

Date: 2008-09-10

Compiling environment: VC ++ 6.0

========================================================== ========================================================== = */

# Include <iostream>
Using namespace STD;

Template <class T>
Void insertsort (T * P, size_t length)
{
T senti; // replace guard P [0]
Int I, J;
For (I = 1; I <length; ++ I)
{
If (P [I] <p [I-1])
{
Senti = P [I];
For (j = I-1; senti <p [J] & J> = 0; -- j) // J> = 0, otherwise, an error occurs.
{
P [J + 1] = P [J];
}
P [J + 1] = senti;
}
}
}

Int main ()
{
Int A [10]; // = {, 35, 62 };
Cout <"input ten integers:" <Endl;
For (INT I = 0; I <10; I ++)
{
Cin> A [I];
}
Cout <Endl;
Insertsort (A, 10 );
Cout <"after sort:" <Endl;
For (Int J = 0; j <10; j ++)
{
Cout <A [J] <"";
}
Return 0;
}

 

 

In fact, there is no big difference with direct insertion sorting, but the search process uses a half-fold query, the total time complexity is still O (N ^ 2), so I can review the half-fold search.

/* ===================================================== ========================================================== =

Function: Performs semi-insert sorting on element arrays that can be compared with <.

Author: sunnyrain

Date: 2008-09-10

Compiling environment: VC ++ 6.0

========================================================== ========================================================== = */

# Include <iostream>
Using namespace STD;

Template <class T>
Void binsertsort (T * P, size_t length)
{
T senti; // replace guard P [0]
Int I, j, low, high, mid;
For (I = 1; I <length; ++ I)
{
Low = 0;
High = I-1;
Mid = (low + high)/2;
While (low <= high) // semi-Query Process
{
If (P [I]> P [Mid])
{
Low = Mid + 1;
Mid = (low + high)/2;
}
Else
{
High = mid-1;
Mid = (low + high)/2;
}
}

Senti = P [I];
For (j = I-1; j> = mid; -- j) // move element & Insert
{
P [J + 1] = P [J];
}
P [high + 1] = senti; // replace J with high here. Otherwise, an error occurs when the inserted element is larger than all the preceding elements.

}
}

Int main ()
{
Int A [10] = };
/* Cout <"input ten integers:" <Endl;
For (INT I = 0; I <10; I ++)
{
Cin> A [I];
}*/
Cout <Endl;
Binsertsort (A, 10 );
Cout <"after sort:" <Endl;
For (Int J = 0; j <10; j ++)
{
Cout <A [J] <"";
}
Return 0;
}

 

 

 

The insertion sorting of the table in the book is not provided to the algorithm. Although it looks very simple, it is still a loop linked list, and it takes a long time to find the correct insertion position. The subsequent shuffling is an algorithm in the book, which is easy to copy.

/* ===================================================== ========================================================== =

Function: insert and sort tables in C ++.

Author: sunnyrain

Date: 2008-09-11

Compiling environment: VC ++ 6.0

========================================================== ========================================================== = */

# Include <iostream>
Using namespace STD;
Const int size = 100;

Template <class T>
Struct slnode {
T ELEM;
Int next;
};

Template <class T>
Struct list {
Slnode <t> r [size];
Int length;
};

Template <class T>
Void tablesort (list <t> & list) // sort table Inserts
{
List. R [0]. Next = 1;
List. R [1]. Next = 0;
For (INT I = 2; I <list. length; I ++)
{
Int J = List. R [0]. Next;
Int pre = 0; // record the previous position of the current node
While (list. R [I]. ELEM> = List. R [J]. ELEM & J> 0) // find the insert position
{
Pre = J;
J = List. R [J]. Next; // The linked list goes one step forward.
}
List. R [I]. Next = J; // The inserted node. the next field points to the J node.
List. R [pre]. Next = I; // the next field of the previous node of the inserted node points to the inserted node.
}
}

Template <class T>
Void arrange (list <t> & list) // rearrange
{
Int pre = List. R [0]. Next;
For (INT I = 1; I <list. length; I ++)
{
While (pre <I)
Pre = List. R [pre]. Next;
Int q = List. R [pre]. Next;
If (pre! = I)
{
Slnode <t> temp = List. R [pre];
List. R [pre] = List. R [I];
List. R [I] = temp;
List. R [I]. Next = pre;
}
Pre = Q;
}
}

Int main ()
{
List <int> list;
Int length = 8;
 
// Cout <"Enter the table length:" <Endl;
// CIN> length;
 
List. Length = Length + 1;
// Cout <"enter" <length <"digits:" <Endl;
 
/* For (INT I = 1; I <list. length; I ++)
{
Cin> list. R [I]. ELEM;
}*/
List. R [1]. ELEM = 49;
List. R [2]. ELEM = 38;
List. R [3]. ELEM = 65;
List. R [4]. ELEM = 97;
List. R [5]. ELEM = 76;
List. R [6]. ELEM = 13;
List. R [7]. ELEM = 27;
List. R [8]. ELEM = 49;
 
For (INT I = 1; I <list. length; I ++)
{
List. R [I]. Next =-1;
}
 
Tablesort (list); // sort table Inserts

Cout <"sorting result (pointer domain order):" <Endl;
For (I = 0; I <Length + 1; I ++)
Cout <list. R [I]. Next <"/t ";
Cout <Endl;

Cout <"reschedule Result:" <Endl;
Arrange (list); // sorts static linked lists.
For (I = 1; I <list. length; I ++)
{
Cout <list. R [I]. ELEM <"/t ";
}
Cout <Endl;
 
For (I = 1; I <list. length; I ++)
{
Cout <list. R [I]. Next <"/t ";
}
Cout <Endl;

Return 0;
}

 

 

 

/* ===================================================== ========================================================== =

Function: Shell sorting C ++

Author: I am not the author of algorithms because they are all copied from books. Yan Weimin, Author: Hey hey

Date: 2008-09-11

Compiling environment: VC ++ 6.0

========================================================== ========================================================== = */

# Include <iostream>
Using namespace STD;

Template <class T>
Void shellinsert (T * P, size_t length, int DK) // shell sorting
{
T temp;
For (INT I = dk; I <length; ++ I)
{
If (P [I] <p [I-dk])
{
Temp = P [I];
For (Int J = I-DK; j> = 0 & temp <p [J]; j-= dk) // insert a row
P [J + dk] = P [J];
P [J + dk] = temp;
}
}
}

Template <class T>
Void shellsort (T * P, size_t length, int dlta [], int T)
{
For (int K = 0; k <t; ++ K)
{
Shellinsert (p, length, dlta [k]);
For (Int J = 0; j <length; j ++) // print the result of each sort.
{
Cout <p [J] <"/t ";
}
Cout <Endl;
}
}

Int main ()
{
Int A [10] = };
Int dlta [] = {9, 5, 3, 1}; // dlta [k] = 2 ^ (t-k) + 1, t = 3
/* Cout <"input ten integers:" <Endl;
For (INT I = 0; I <10; I ++)
{
Cin> A [I];
}
Cout <Endl ;*/
Shellsort (A, 10, dlta, 4 );
Cout <"after sort:" <Endl;
For (Int J = 0; j <10; j ++)
{
Cout <A [J] <"";
}
Return 0;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.