C # Data structures and algorithms-linear structure

Source: Internet
Author: User

In this article, we discussed three parts of the content:

    1. What are linear structures and what are the characteristics of linear structures?

    2. The simplest linear structure sequential table is described in detail, and some analysis is done by source code.

    3. Finally, an example is given to give us a better understanding of the sequential table.


Part I: What are linear structures and what are the characteristics of linear structures?

What is linear structure, linear structure is the simplest, most basic, most commonly used data structure. Linear table is the abstract of linear structure, and the characteristic of linear structure is that there exists a one-to linear relationship between data elements in structure. This

A one-to-one relationship refers to the positional relationship between data elements, namely: (1) In addition to the first position of the data element, the location of the other data element is preceded by a data element, (2) In addition to the last position of the data element, the other data element location behind only one element. That is, the data element is arranged one after the other. 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 of data elements of the same type as n (n≥0). Two concepts should be noted for this definition: one is "finite", which refers to the finite number of data elements in a linear table, and each data element in a linear table has its own position (Position). This book does not discuss linear tables with an infinite number of data elements. The second is "same type", which refers to the same type of data elements in a linear table. This is reflected in our commonly used data structures are arrays, generics and so on they are linear structure.

The relationship between them is: Linear table is formally defined as: Linear table (list) précis-writers for L, is a two-tuple, L = (d, R) where: D is a finite set of data elements. R is a limited set of relationships between data elements.

The basic operation of the linear structure is as follows:

Public interface Ilistds<t> {
int GetLength (); Request length
void Clear (); Clear operation
BOOL IsEmpty (); Determine if 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's why Ilistds is with. NET comes with the IList phase difference. The explanations for each method are as follows:

1. Length: GetLength ()
Initial conditions: linear table exists;
Operation Result: Returns the number of all data elements in the linear table.
2. Clear operation: Clear ()
Initial conditions: Linear tables exist and have data elements;
Operation Result: Clears all data elements from the linear table and the linear table is empty.
3. Determine if the linear table is empty: IsEmpty ()
Initial conditions: linear table exists;
Operation Result: Returns TRUE if the linear table is null, otherwise false.
4. Additional operation: Append (T Item)
Initial conditions: the linear table exists and is not full;
Action Result: Adds a new element with a value of item to the end of the table.
5. Insert operation: Insert (T item, int i)
Initial conditions: the linear table exists and the insertion position is correct (1≤i≤n+1,n is the length of the table before insertion).
Operation Result: Inserts a new element with the value of item in the first position of the linear table so that the ordinal of the data element with the original ordinal i,i+1,..., n becomes i+1,i+2,..., n+1, and the table length after insertion = The original table length +1.
6. Delete operation: Delete (int i)
Initial conditions: the linear table exists and is not empty, and the delete position is correct (1≤i≤n,n is the length of the table before deletion).
Operation Result: Delete the data element with ordinal I in the linear table and return the deleted data element. After deletion, the ordinal of the data element with the original ordinal i+1,i+2,..., n becomes i,i+1,..., n-1, and the table length after deletion = The original table length-1.
7, take the Table element: Getelem (int i)
Initial conditions: the linear table exists and the data element is positioned correctly (1≤i≤n,n is the table length of the linear table); Operation Result: Returns the first data element in a linear table.
8. Search by Value: Locate (T value)
Initial conditions: a linear table exists.
Action Result: Finds a data element with value in a linear table whose result returns the ordinal of a data element that first appears in a linear table, called value, which is found to be successful; otherwise, a data element with value values in the linear table is returned, and a special value indicates that the lookup failed.


Part II: A simplest linear structure sequence table and source code analysis


Look at the simplest linear structure--sequential table

What is sequential table, the sequential storage of linear structure refers to the data element of linear table which is stored sequentially in memory with a contiguous space of one address, in this way the linear is called sequential table (Sequence list).

Sequential table storage Structure

650) this.width=650; "Width=" 620 "height=" "src=" http://files.jb51.net/file_images/article/201211/ 2012110120461110.png "/>


Assuming that each data element in the sequential table occupies a W storage unit, and that the storage address for the first Data element is LOC (AI), then there is the LOC (ai) = loc (A1) + (I-1) *w 1≤i≤n, which represents the storage address of the data element A1, is also the starting storage address of the sequential table, called the base address of the sequential table. Here we give an example, for example, when you go to the hotel, know the base of room 101th, you have to go to room 111th, you know the distance between each room is 5, there is only 50 meters forward. The address operation of the sequential table is so simple.

The sequential table is the inheritance and the linear structure, and his source code is this way.

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

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

Last Data Element Location property
public int Last
{
Get
{
return last;
}
}

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

Set
{
MaxSize = value;
}
}

Constructors Perform function initialization work

public seqlist (int size)

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

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

Empty Order table

Clearing the data elements in the sequential table is to make the order table empty, at which point the last equals-1.

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

Determine if the order table is empty

If the last of the sequential table is-1, the order table is empty and returns true, otherwise false is returned.
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 last equals maxsize-1, otherwise false is returned.
public bool Isfull ()
{
if (last = = maxsize-1)
{
return true;
}
Else
{
return false;
}
}
An additional action is to add a new element at the end of the table, and then append 1 to the last of the order table, in the case of a sequence table that is not full.

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 sequential tables is the insertion of a new element with a value of item in the first place of the order table, a table (A1,A2, ..., ai-1,ai,ai+1, ..., an) that is inserted so that the original table is an n, which becomes a table with a table length of n+1 (A1,a2,..., Ai-1,item , Ai,ai+1,..., an). When the value range for I is 1≤i≤n+1,i to n+1, the data element is inserted at the end of the order table. The steps for inserting a data element on a sequential table are as follows:

//(1) Determine if the order table is full and the position inserted is correct, the table full or inserted position is incorrect, cannot be inserted;  //(2) If the table is not full and the position is inserted correctly, Moves the An~ai back in order to empty the position for the new data element. The algorithm is implemented by loops;  //(3) Inserts the new data element into the vacated  i  position;  //(4) modifies the  last (equivalent to the modified table length)  , so that it still points to the last data element in the sequential table.  //inserts a data element  public void insert (t item, int i)  { if in the position of the first data element of the sequential table   (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&NBSP;J&NBSP;=&NBSP;LAST;&NBSP;J>=&NBSP;I-1;&NBSP;--J)  {  data[j + 1] = data[j]; }data[i-1] = item; } ++last; } 

The time complexity analysis of the algorithm: the insert operation on the sequential table, the time mainly consumes on the data movement, inserts an element in the first place, from Ai to an to move backward one position, altogether needs to move n-i+1
element, and I has a value range of 1≤i≤n+1, when I equals 1 o'clock, the number of elements that need to be moved is the largest, n, and when I is n+1, no moving element is required. The probability of inserting in the first position is pi, then the 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 the data elements in the table to be moved, so the time complexity of the insert operation is O (n).


The delete operation of the sequential table refers to the deletion of the first Data element in the table from the sequential table, and the table with the original table (A1,A2, ..., Ai-1,ai, ai+1, ..., an) changed to a table with a table length of n-1 (a1,a2,..., ai-1,ai+1,..., an). When the value range of I is 1≤i≤n,i to n, the data element at the end of the delete order table is deleted.

The steps to delete a data element on a sequential table are as follows:
(1) Determine if the order table is empty and the location of the deletion is correct, the table is empty or the location of the deletion is incorrect
Can not be deleted;
(2) If the table is not empty and the location of the deletion is correct, the Ai+1~an will move forward in turn. In the algorithm
using loops to achieve;
(3) Modify 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 the Order table public T Delete (int i) {t tmp = default (T), if (IsEmpty ()) {Console.WriteLine ("List is empty"); return T mp }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; }

Time complexity analysis of the algorithm: the delete operation on the sequential table is the same as the insert operation, the time is mainly consumed on the data movement. Delete an element in the first place, from Ai+1 to an to move forward a position, the total need to move n-i elements, and I the value range is 1≤i≤n, when I equals 1 o'clock, the number of elements that need to move the most, is n-1, when I is N, there is no need to move the element. The probability of deletion in the first position is pi, then the average number of moving data elements is (n-1)/2. This means that the delete 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 delete operation is O (n).


The fetch TABLE element operation is to return the first Data element in the order table, and the range of the values of I is 1≤i≤last+1. Since the table is randomly accessed, the time complexity of taking a TABLE element operation is O (1) If the value of I is correct.

Get the I data element of the sequential table
Public T Getelem (int i)
{
if (IsEmpty () | | | (i<1) | | (i>last+1))
{
Console.WriteLine ("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 satisfy a given value.

The simplest way to do this in a sequential table is to compare the first element to the given value, and, if found, to return the ordinal of the first occurrence of the data element equal to the given value in the sequential table, which is known as a successful lookup;

In the sequential table, look for a data element with value of 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; } }


Time complexity analysis of the algorithm: the primary operation for lookup by value in a sequential table is a 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 a given value is equal to the first Data element, the number of comparisons is 1, and when the given value is equal to the last element, the number of comparisons is N. Therefore, the average number of comparisons is (n+1)/2, and the time complexity is O (n).


The third part: the example illustrates, writes an algorithm to turn the order table upside down.

such as: Known order table L, write an algorithm to invert it, where (a) is inverted before, (b) is inverted.

My thinking is to change the middle number of the position. 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 simply scans the sequence of data elements in the order table once and then completes the inversion, so the time complexity is O (n). The effect of the operation:


650) this.width=650; "src=" Http://files.jb51.net/file_images/article/201211/2012110120461111.png "/>


Reference: http://www.jb51.net/article/31696.htm

This article comes from the "Ricky's blog" blog, please be sure to keep this source http://57388.blog.51cto.com/47388/1663502

C # Data structures and algorithms-linear structure

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.