C # Data structure and algorithm revelation two _c# tutorial

Source: Internet
Author: User
Tags data structures int size

The above data structure and algorithm, there is a simple overview and introduction, this article, we introduce a typical data structure-linear structure.

What is linear structure, linear structure is the simplest, most basic, most commonly used data structure. The linear table is the abstract of the linear structure, and the linear structure is characterized by a one-to-one linear relationship between the data elements in the structure. This

A one-to-one relationship refers to the position relationship between data elements, that is: (1) Except for the data element in the first position, there is only one data element in front of the position of the other data element, (2) except for the data element in the last position, there is only one element at the back of the position of the data element. In other words, the data elements are arranged one after another. Therefore, the linear structure can be imagined as a data structure of a sequence of data elements.

A linear structure (List) is a finite sequence consisting of n (n≥0) data elements of the same type. Two concepts should be noted for this definition: one is "limited", meaning that the number of data elements in a linear table is limited, and each data element in a linear table has its own position (Position). This book does not discuss linear tables with infinite number of data elements. The second is "same type", which means that the data elements in the linear table belong to the same type. This is reflected in our commonly used data structures are arrays, generics and so on they are all linear structures.

The relationship between them is: the formal definition of the linear table is: Linear table (list) denoted is L, is a two-tuple, L = (d, R) where: D is a finite set of data elements. R is a finite set of relationships between data elements.

The basic operation of the linear structure is as follows:

Public interface Ilistds<t> {
int GetLength (); Find the length
void Clear (); Empty operation
BOOL IsEmpty (); To determine whether a linear table is empty
void Append (T item); Additional actions
void Insert (T item, int i); Insert operation
T Delete (int i); Delete operation
T Getelem (int i); Take a TABLE element
int Locate (T value); Find by value
}

Here why is Ilistds is with. NET IList is different from the band. The explanations for each method are as follows:

1, to find the length: GetLength ()
Initial condition: linear table exists;
Action Result: Returns the number of all data elements in a linear table.
2. Empty operation: Clear ()
Initial condition: Linear table exists and has data elements;
Action Result: Clears all data elements from the linear table, and the linear table is empty.
3, to determine whether the linear table is empty: IsEmpty ()
Initial condition: linear table exists;
Action Result: Returns FALSE if the linear table returns True if it is null.
4. Additional operation: Append (T Item)
Initial condition: the linear table exists and is not full;
Action Result: Adds a new element with the value item to the end of the table.
5, insert operation: Insert (T item, int i)
Initial condition: the linear table exists, the insertion position is correct (1≤i≤n+1,n is the table length before inserting).
Action Result: Inserts a new element of item on the first position of the linear table, so that the ordinal number of the data element with the original ordinal number i,i+1,..., n changes to the i+1,i+2,..., n+1, and the table length after insertion = +1 of the original table.
6. Delete operation: Delete (int i)
Initial condition: the linear table exists and is not empty, and the deletion position is correct (1≤i≤n,n is the table length before deletion).
Action Result: Deletes the data element with ordinal number I in the linear table, and returns the deleted data element. After deletion, the ordinal number of the data element with the original ordinal number i+1,i+2,..., n is changed to I,i+1,..., n-1, and the table length = 1 after deletion.
7, take the Table element: Getelem (int i)
Initial condition: the linear table exists, the data element position is correct (1≤i≤n,n is the table length of the linear table); Action Result: Returns the first data element in a linear table.
8, search by value: Locate (T value)
Initial condition: Linear table exists.
Operation Result: Finding a data element in a linear table that evaluates to value, returns the ordinal of the data element whose first occurrence in the linear table is value, called a lookup success, otherwise, a special value is returned in the linear table that indicates the lookup failure.

First look at the simplest linear structure--The order table

What is a sequential table, the linear structure of sequential storage is in memory with a single address contiguous space in order to store the data elements of the linear table, in this way stored linear is called the Order table (Sequence list).

Sequential table storage structure as shown in the figure

Assuming that each data element in the sequential table occupies a W storage unit, the storage address for the I data element is Loc (AI), then there are: Loc (ai) = Loc (A1) + (I-1) *w 1≤i≤n (LOC) represents the storage address of the first Data element A1. Also is the starting storage address of the sequential table, called the base address of the sequential table. Here, for example, when you go to a hotel, you know the benchmark of room 101th, you have to go to room 111th, you know the distance between each room is 5, there only need to advance 50 meters. The address operation of a sequential table is as simple as that.

and the sequential table is inherited and linear structure, and his source code is like this.

public class Seqlist<t>: ilistds<t> {
private int maxsize; Maximum capacity of the Order table's Capacity order table
Private t[] data; An array that stores the structure of data elements in a sequential table for storing sequential tables
private int last; Indicates the position of the last element in the order table

Indexing device
Public T This[int Index]
{
Get
{
return Data[index];
}
Set
{
Data[index] = value;
}
}

Last data Element position attribute
public int Last
{
Get
{
return to last;
}
}

Capacity Properties
public int Maxsize
{
Get
{
return maxsize;
}

Set
{
MaxSize = value;
}
}

Constructor for function initialization work

public seqlist (int size)

{
data = new T[size];
maxsize = size;
last =-1;
}

To find the length of the order table
public int GetLength ()
{
return last+1;
}

Empty Order table

Clears the data element in the order table so that the order table is empty, at which point the last equals-1.

public void Clear ()
{
last =-1;
}

Determine if the order table is empty

If the order table has the last of-1, the order table is empty, returns True, or returns false.
public bool IsEmpty ()
{
if (last = = 1)
{
return true;
}
Else
{
return false;
}
}


Determine if the order table is full

Returns true if the order table is full and the last equals maxsize-1, otherwise false.
public bool Isfull ()
{
if (last = = maxsize-1)
{
return true;
}
Else
{
return false;
}
}
The additional action is to add a new element at the end of the table when the order table is not full and then add 1 to the last of the sequential table.

Add a new element at the end of a sequential table
public void Append (T item)
{
if (Isfull ())
{
Console.WriteLine ("List is full");
Return
}

Data[++last] = Item;
}
The insertion of a sequential table is the insertion of a new element of item at the first position in the order table (A1,A2, ..., ai-1,ai,ai+1, ..., an) to become a table with a table length of n+1 (A1,a2,..., Ai-1,item , Ai,ai+1,..., an). When the range of I is 1≤i≤n+1,i to n+1, it represents inserting a data element at the end of the sequential table. The steps for inserting a data element on a sequential table are as follows:

(1) To determine whether the sequence table is full and inserted in the correct position, the table full or inserted in the wrong position can not be inserted;
(2) If the table is not full and the inserted position is correct, move the An~ai backward in turn, and empty the position for the new data element. In the algorithm with the loop to achieve;
(3) inserting the new data element into the vacated first position;
(4) Modify the last (equivalent to modifying the table length) so that it still points to the final data element of the sequential table.

Inserts a data element at the position of the first Data element in the order table
public void Insert (T item, int i)
{
if (Isfull ())
{
Console.WriteLine ("List is full");
Return
}

if (i<1 | i>last+2)
{
Console.WriteLine ("Position is error!");
Return
}

if (i = = last + 2)
{
DATA[LAST+1] = Item;
}
Else
{
for (int j = last; j>= i-1;--j)
{
Data[j + 1] = Data[j];
}

DATA[I-1] = Item;
}
++last;
}

The time complexity analysis of the algorithm: the insertion operation on the sequential table, the time is mainly consumed in the data movement, in the first position inserts an element, from AI to an to move backward one position, altogether needs to move n-i+1
element, and I's range is 1≤i≤n+1, when I equals 1 o'clock, the number of elements that need to be moved is the most, n, and when I is n+1, there is no need to move the element. The probability of inserting at position i is pi, then flat
The number of times the data element is moved is N/2. This means that the insertion operation on the sequential table requires an average of half of the data elements in the table to be moved, so the time complexity of the insert operation is O (n).

The deletion of a sequential table means that the first Data element in the table is deleted from the Order table. A table (A1,A2, ..., Ai-1,ai, ai+1, ..., an) that makes the original table long as n is deleted (a1,a2,..., ai-1,ai+1,..., an). The value range of I is 1≤i≤n,i N, which indicates that the data element at the end of the order table is deleted.

The steps to delete a data element on a sequential table are as follows:
(1) To determine whether the order table is empty and the location of the deletion is correct, the table empty or deleted location is not
Can not be deleted;
(2) If the table is not empty and the deletion position is correct, the Ai+1~an is moved forward sequentially. In the algorithm
using loops to achieve;
(3) Modify the last (equivalent to modifying the table length) so that it still points to the final element of the sequential table.

Delete the first data element of a sequential table
Public T Delete (int i)
{
t tmp = default (t);
if (IsEmpty ())
{
Console.WriteLine ("List is empty");
return TMP;
}

if (I < 1 | i > Last+1)
{
Console.WriteLine ("Position is error!");
return TMP;
}

if (i = = last+1)
{
TMP = data[last--];
}
Else
{
TMP = data[i-1];
for (int j = i; J <= last; ++j)
{
DATA[J] = data[j + 1];
}
}

--last;
return TMP;
}

The time complexity analysis of the algorithm: the deletion operation on the sequential table is the same as the insert operation, the time is mainly consumed in the data movement. Delete an element in the first position, from Ai+1 to an to move forward a position, the total need to move n-i elements, and I of the range of 1≤i≤n, when I equals 1 o'clock, the number of elements that need to move most, for n-1; When I is n, you do not need to move the element. The probability of a deletion at position i is pi, and the average number of data elements moved is (n-1)/2. This means that the deletion operation on the order table requires an average of half of the data elements in the table to be moved, so the time complexity of the delete operation is O (n).

The fetch-element operation is the first Data element in the return order table, and the value range of I is 1≤i≤last+1. Because tables are randomly accessed, the time complexity of taking a TABLE element is O (1) If I is correctly evaluated.

Get the first data element of a sequential table
Public T Getelem (int i)
{
if (IsEmpty () | | (i<1) | | (i>last+1))
{
Console.WriteLine ("The List is empty or Position is error!");
return default (T);
}

return data[i-1];
}
Lookup by value in a sequential table refers to finding data elements in a table that meet a given value. The simplest way to complete the operation in a sequential table is to: the first element, in turn, is compared to the given value and, if found, returns the ordinal of the data element that first appears in the order table that is equal to the given value, called the lookup success;

Find data elements in a sequential table that value is values
public int Locate (T value)
{
if (IsEmpty ())
{
Console.WriteLine ("List is empty!");
return-1;
}

int i = 0;
for (i = 0; I <= last; ++i)
{
if (value. Equals (Data[i])
{
Break
}
}

if (i > Last)
{
return-1;
}
return i;
}
}

The time complexity analysis of the algorithm: the primary operation for searching by value in the sequential table is comparison, and the number of comparisons is related to the position of the given value in the table and the length of the table. When the given value is equal to the first data element, the comparison is 1, and the number of comparisons is n when the given value is equal to the last element. Therefore, the average number of comparisons is (n+1)/2, and the time complexity is O (n).

For example, a known sequential table L, which writes an algorithm upside down, implements the operation shown in Figure 2.4, where (a) is inverted before, (b) is inverted.

I think of the idea is to be in the middle number of the exchange. The corresponding source code is as follows:

public void Reversseqlist (seqlist<int> L)
{
int tmp = 0;
int len = L.getlength ();
for (int i = 0; i<= len/2; ++i)
{
TMP = L[i];
L[i] = l[len-i];
L[len-i] = tmp;
}
}

The algorithm only scans the sequence of the data elements in order to complete the inversion, so the time complexity is O (n). The running effect is as shown in the figure:

Also, for example, I've been developing my own experience in Tetris, where my sequential structure is really a lot of things, such as the initialization process.

Initializes a collection of shapes with seven shapes
_pieces = new List<piecebase> {new I (), New L (), New I2 (), New L2 (), New N (), New N2 (), New O (), New T ()};
Initialize the box container (fills the entire container with the Block object)
Container = new block[_rows, _columns];
for (int i = 0; i < _rows; i++)
{
for (int j = 0; J < _columns; J + +)
{
var block = new block ();
Block. top = i * block.rectangle.ActualHeight;
Block. left = J * Block.rectangle.ActualWidth;
Block. Color = null;
Container[i, j] = block;
}
}

Initializes the container for the next shape (fills it with a block object)
Nextcontainer = new block[4, 4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; J < 4, j + +)
{
var block = new block ();
Block. top = i * block.rectangle.ActualHeight;
Block. left = J * Block.rectangle.ActualWidth;
Block. Color = null;
Nextcontainer[i, j] = block;
}
}

Create a new shape
Createpiece ();
Renders the currently created shape
Addpiece (0, 0);

Timer is used to move shapes down at timed intervals
_timer = new DispatcherTimer ();
_timer. Interval = Timespan.frommilliseconds (_initspeed);
_timer. Tick + = _timer_tick;
GameStatus = Gamestatus.ready;

You look at the initialization box I used, the container is a two-dimensional array, which is an obvious order table. Assign a value to his top position, left position, and perform a series of initialization tasks. This is equivalent to a sequential table initialization operation. The complexity of this algorithm is O (n²).

In this article, we discussed what is the linear structure, what is the characteristics of the linear structure, and detailed introduction of a simple linear structure order table, and through the source code to some of her column analysis, and finally gave two examples, let us better understand the sequence table.

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.