Tải bản đầy đủ (.ppt) (83 trang)

Bài giảng Lập trình Windows - Chương 8: Arrays

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.04 MB, 83 trang )

Chương 8 - Arrays
• Giới thiệu
• Khai báo
• Cách sử dụng mảng
• Các giải thuật cơ bản trên mảng
• Các phương thức của mảng
• Các đối tượng mảng trên C#

1


Giới Thiệu
• Mảng là kiểu dữ liệu có cấu trúc bao gồm
nhiều phần tử cùng kiểu và được đặt liên
tiếp trong vùng nhớ.
• Mỗi phần tử của mảng được tham chiếu
thơng qua chỉ mục (index). Nếu mảng có n
phần tử thì phần tử đầu tiên có chỉ mục là 0
và phần tử cuối có chỉ mục là n-1. Cách tham
chiếu một phần tử là tenmang[chỉ mục].
• Mảng có kích thước là số phần tử trong
mảng.

2


Giới Thiệu
(0)
(1)
(2)
(3)


(4)
(5)
(6)
(7)
(8)
(9)

Janet Baker
George Lee
Sue Li
Samuel 
Hoosier
Sandra Weeks
William Macy
Andy Harrison
Ken Ford
Denny Franks
Shawn James

Fig. 7.1

A 12-element array.

Name of array
(Note that all
elements of this
array have the
same name, c)

Position number

(index or
subscript) of the
element within
array c

3

c[ 0 ]

-45

c[ 1 ]

6

c[ 2 ]

0

c[ 3 ]

72

c[ 4 ]

1543

c[ 5 ]

-89


c[ 6 ]

0

c[ 7 ]

62

c[ 8]

-3

c[ 9 ]

1

c[ 10 ]

6453

c[ 11 ]

-78


Khai báo và khởi tạo Mảng


Khai báo

<Datatype> [ ] <NameArray>;
Ex:

int[ ] c;



Tạo mảng, gán giá trị cho biến mảng
<NameArray> = new <Datatype> <[ARRAY_SIZE]>;
Ex :
c = new int[ 12 ];

int [ ] c = new int[ 12 ];

4


Ví dụ sử dụng mảng
void Main( string[] args )
{
string output = "";
int[] x;
x = new int[ 10 ];
int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
const int ARRAY_SIZE = 10;
int[] z;
z = new int[ ARRAY_SIZE ];
for ( int i = 0; i < z.Length; i++ )
z[ i ] = 2 + 2 * i;
for ( int i = 0; i < ARRAY_SIZE; i++ )

output += z[ i ] + "\t";
}

5


Ví dụ sử dụng mảng
int[] aa ==
int[]
int total
total
int

{{
==

1, 2,
2, 3,
3, 4,
4, 5,
5, 6,
6, 7,
7, 8,
8, 9,
9, 10
10 };
};
1,
0;
0;


for (( int
int
for
total
total

0; ii << a.Length;
a.Length; i++
i++ ))
ii == 0;
+= a[
a[ ii ];
];
+=

6


Truyền Mảng vào Hàm (Phương
thức)
• Để truyền Mảng vào Hàm, ta chỉ định tên của
mảng.
• Có 2 cách truyền:
– Truyền theo giá trị (Value)
– Truyền theo địa chỉ (Reference)

7



8

Truyền Mảng vào Hàm (Phương thức)

// method modifies the array it receives,
// original will be modified
public void ModifyArray( int[] b )
{
for ( int j = 0; j < b.Length; j++ )
b[ j ] *= 2;
}


Truyền Mảng vào Hàm (Phương thức)
int[] a = { 1, 2, 3, 4, 5 };
outputLabel.Text = "Effects of passing entire
array " + "call-by-reference:\n\nThe values of
the original " + "array are:\n\t";
for ( int i = 0; i < a.Length; i++ )
outputLabel.Text += "
" + a[ i ];
ModifyArray( a );// array is passed by reference
ModifyElement( a[ 3 ] ); // array element passed
call-by-value

9


Truyền Mảng vào Hàm (Phương
thức)

• Truyền theo giá trị
– Tạo một bản sao của biến mảng
– Bất kỳ thay đổi nào của biến mảng trong hàm cũng
không ảnh hưởng đến giá trị của biến gốc.

• Truyền theo địa chỉ
– Tạo ra một bản sao tham khảo tới đối tượng.
– Bất kỳ những thay đổi tới những tham khảo trong
phương thức không làm ảnh hưởng đến biến gốc.
– Bất kỳ những thay đổi nội dung của đối tượng trong
phương thức làm ảnh hưởng đến đối tượng ngoài
phương thức.

10


Các giải thuật cơ bản trên
mảng
• Các thao tác cơ bản trên mảng 1 chiều:
• Nhập giá trị cho các phần tử mảng.
• Xuất giá trị các phần tử mảng (ra màn hình).
• Thêm 1 phần tử vào mảng.
• Xóa một phần tử ra khỏi mảng.
• Tìm kiếm trên mảng.
• Sắp xếp mảng.

11


Nhập xuất Array

Nhập, xuất thực chất là gán hoặc lấy giá trị của array tại
vị trí nào đó. Thơng thường nhập xuất mảng kết hợp
vịng lặp.
Ví dụ nhập mảng:
int [] A= new int [50];
Random n = new Random();
int i=0;
while (i < A.Length)
{
A[i] = n.Next(1, 91);// nhập cho item thứ i
i++;
}

12


Nhập xuất Array
Ví dụ truy xuất Array:

long t = 0;
while (i < A.Length)
{
t += A[i];
i++;
}

13


Nhập xuất Array

Truy xuất các phần tử trong array dùng cấu trúc lặp
for each rất hiệu quả.
Cú pháp
foreach ( type identifier in arrayName )
statement

14


Nhập xuất Array
Truy xuất qua vị trí

Truy xuất qua foreach

long tongmang(int[] A)
{
int i = 0, x;
long t = 0;
while (i < A.Length)
{
x = A[i];
t += x;
i++;
}
return t;
}

long tongmangForeach(int[] A)
{
long t = 0;

foreach (int x in A)
{
t += x;
}
return t;
}

15


Sắp xếp Mảng - Sorting
Arrays
• Sắp xếp các phần tử tăng dần
private void sap_xep_tang_dan()
{ int i, j;
for (i = 0; i < mang_nguyen.Length - 1; i++)
{ for (j = i + 1; j < mang_nguyen.Length; j++)
{
if (mang_nguyen[i] > mang_nguyen[j])
{ // nếu gặp phần tử nhỏ hơn thì đổi chỗ
int tam = mang_nguyen[i];
mang_nguyen[i] = mang_nguyen[j];
mang_nguyen[j] = tam;
} //if
} // for j
} // for i
}

16



Sắp xếp Mảng - Sorting
Arrays

17


18
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

// Fig. 7.10: BubbleSorter.cs
// Sorting an array's values into ascending order.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

BubbleSort
er.cs

public class BubbleSorter : System.Windows.Forms.Form
{
private System.Windows.Forms.Button sortButton;
private System.Windows.Forms.Label outputLabel;

// Visual Studio .NET generated code

Declare and initialize array a

[STAThread]
static void Main()
{
Application.Run( new BubbleSorter() );
}

Output the contents of array a
Call method Bubble sort on array a

private void sortButton_Click( object sender,
System.EventArgs e )
{
int[] a = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
outputLabel.Text += "Data items in original order\n";
for ( int i = 0; i < a.Length; i++ )
outputLabel.Text += "
" + a[ i ];
// sort elements in array a
BubbleSort( a );


19
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

outputLabel.Text += "\n\nData items in ascending order\n";
for ( int i = 0; i < a.Length; i++ )
outputLabel.Text += "
" + a[ i ];
} // end method sortButton_Click


Swaps two elements
of an array
BubbleSort
If an given element is bigger
Output
sorted array
a
er.cs
then the following
element,

// sort the elements of an array with bubble sort
swap the elements
public void BubbleSort( int[] b )
{
for ( int pass = 1; pass < b.Length; pass++ ) // passes
for ( int i = 0; i < b.Length - 1; i++ )
if ( b[ i ] > b[ i + 1 ] )
Swap( b, i );
}

// one pass

// one comparison
// one swap

Perform
contents of for loop
Perform b.Length-1

passes
for each element of array b

// swap two elements of an array
public void Swap( int[] c, int first )
{
int hold;
// temporary holding area for swap
hold = c[ first ];
c[ first ] = c[ first + 1 ];
c[ first + 1 ] = hold;
}
}


Tìm kiếm: Linear Search and Binary
Search
• Tìm kiếm tuyến tính: Linear Search
• Tìm kiếm nhị phân: Binary Search

20


Tìm kiếm: Linear Search and Binary
Search
• Tìm kiếm tuyến tính: Linear Search
int LinearSearch(int a[], int n, int x)

{
for (int i=0; i

if (a[i]==x) return i;
return –1;
}

21


22
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

// Fig. 7.11: LinearSearcher.cs
// Demonstrating linear searching of an array.
using System;
using System.Drawing;
using System.Collections;
Retrieve the number user
using System.ComponentModel;
using System.Windows.Forms;
input as the search key
using System.Data;
public class LinearSearcher : System.Windows.Forms.Form
{
private System.Windows.Forms.Button searchButton;
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.Label outputLabel;

Perform linear search
for the search key


int[] a = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26,
28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50 };
// Visual Studio .NET generated code
[STAThread]
static void Main()
{
Application.Run( new LinearSearcher() );
}
private void searchButton_Click( object sender,
System.EventArgs e )
{
int searchKey = Int32.Parse( inputTextBox.Text );
int elementIndex = LinearSearch( a, searchKey );

LinearSear
cher.cs


23
34
35
36
37
38
39
40
41
42
43

44
45
46
47
48
49
50
51
52
53
54
55
56

if ( elementIndex != -1 )
outputLabel.Text =
"Found value in element " + elementIndex;
else
outputLabel.Text = "Value not found";
} // end method searchButton_Click

LinearSear
cher.cs
If the index of the search key is –
1, then element was not found

// search array for the specified key value
public int LinearSearch( int[] array, int key )
{
If search failed,

for ( int n = 0; n < array.Length; n++ )
{
if ( array[ n ] == key )
Start at beginning of array
return n;
Check every element to see if it
}
return -1;
} // end method LinearSearch
} // end class LinearSearcher

matches the search key.
If it does, return the current index

return -1


Tìm kiếm: Linear Search and Binary
Search
• Tìm kiếm nhị phân: Binary Search
int BinarySearch(const int a[], int n, int x)
{
int first=0, last=n-1, mid;
while(first<=last) {
mid = (first + last) / 2;
if (a[mid]first= mid + 1; // tìm x ở phần nửa sau của mảng
else if (a[mid]>x) last = mid – 1;
else // a[mid]==x
return i; }


return –1;
}

24


25
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

// Fig. 7.12: BinarySearchTest.cs
// Demonstrating a binary search of an array.
using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;


Declare and initialize
integer array a

public class BinarySearchTest : System.Windows.Forms.Form
{
private System.Windows.Forms.Label promptLabel;
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.Label resultLabel;
private System.Windows.Forms.Label displayLabel;
private System.Windows.Forms.Label outputLabel;
private System.Windows.Forms.Button findButton;
private System.ComponentModel.Container components = null;
int[] a = { 0, 2, 4, 6, 8, 10, 12, 14, 16,
18, 20, 22, 24, 26, 28 };
// Visual Studio .NET generated code
// main entry point for application
[STAThread]
static void Main()
{
Application.Run( new BinarySearchTest() );
}

BinarySear
chTest.cs


×