Bài giảng Lập trình Windows - Chương 6: Mảng (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# 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.

ppt83 trang | Chia sẻ: candy98 | Lượt xem: 451 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Bài giảng Lập trình Windows - Chương 6: Mảng (Arrays), để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
1Chươ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#2Giới ThiệuMả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.3Fig. 7.1 A 12-element array. -4560721543-89062-316453-78Position number (index or subscript) of the element within array cName of array (Note that all elements of this array have the same name, c)c[ 11 ]c[ 10 ]c[ 9 ]c[ 8]c[ 7 ]c[ 4 ]c[ 3 ]c[ 2 ]c[ 1 ]c[ 0 ]c[ 6 ]c[ 5 ]Giới Thiệu(0)(1)(2)(3)(4)(5)(6)(7)(8)(9)Janet BakerGeorge LeeSue LiSamuel HoosierSandra WeeksWilliam MacyAndy HarrisonKen FordDenny FranksShawn James4Khai báo [ ] ;Ex: int[ ] c; Tạo mảng, gán giá trị cho biến mảng = new ;Ex : c = new int[ 12 ]; int [ ] c = new int[ 12 ];Khai báo và khởi tạo Mảng5Ví 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 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}17Sắp xếp Mảng - Sorting Arrays18BubbleSorter.cs1 // Fig. 7.10: BubbleSorter.cs2 // Sorting an array's values into ascending order.3 using System;4 using System.Drawing;5 using System.Collections;6 using System.ComponentModel;7 using System.Windows.Forms;8 using System.Data;9 10 public class BubbleSorter : System.Windows.Forms.Form11 {12 private System.Windows.Forms.Button sortButton;13 private System.Windows.Forms.Label outputLabel;14 15 // Visual Studio .NET generated code16 17 [STAThread]18 static void Main() 19 {20 Application.Run( new BubbleSorter() );21 }22 23 private void sortButton_Click( object sender, 24 System.EventArgs e )25 {26 int[] a = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };27 28 outputLabel.Text += "Data items in original order\n";29 30 for ( int i = 0; i b[ i + 1 ] ) // one comparison51 Swap( b, i ); // one swap52 }53 54 // swap two elements of an array55 public void Swap( int[] c, int first )56 {57 int hold; // temporary holding area for swap58 59 hold = c[ first ];60 c[ first ] = c[ first + 1 ];61 c[ first + 1 ] = hold;62 }63 }Output sorted array aPerform b.Length-1 passesPerform contents of for loop for each element of array bIf an given element is bigger then the following element, swap the elementsSwaps two elements of an array20Tìm kiếm: Linear Search and Binary SearchTìm kiếm tuyến tính: Linear SearchTìm kiếm nhị phân: Binary Search21Tìm kiếm: Linear Search and Binary SearchTìm kiếm tuyến tính: Linear Searchint LinearSearch(int a[], int n, int x){ for (int i=0; ix) last = mid – 1; else // a[mid]==x return i; } return –1; }25BinarySearchTest.cs1 // Fig. 7.12: BinarySearchTest.cs2 // Demonstrating a binary search of an array.3 4 using System;5 using System.Drawing;6 using System.Collections;7 using System.ComponentModel;8 using System.Windows.Forms;9 using System.Data;10 11 public class BinarySearchTest : System.Windows.Forms.Form12 {13 private System.Windows.Forms.Label promptLabel;14 15 private System.Windows.Forms.TextBox inputTextBox;16 17 private System.Windows.Forms.Label resultLabel;18 private System.Windows.Forms.Label displayLabel;19 private System.Windows.Forms.Label outputLabel;20 21 private System.Windows.Forms.Button findButton;22 23 private System.ComponentModel.Container components = null;24 25 int[] a = { 0, 2, 4, 6, 8, 10, 12, 14, 16,26 18, 20, 22, 24, 26, 28 };27 28 // Visual Studio .NET generated code29 30 // main entry point for application31 [STAThread]32 static void Main() 33 {34 Application.Run( new BinarySearchTest() );35 }Declare and initialize integer array a26BinarySearchTest.cs36 37 // searches for an element by calling38 // BinarySearch and displaying results39 private void findButton_Click( object sender, 40 System.EventArgs e )41 {42 int searchKey = Int32.Parse( inputTextBox.Text );43 44 // initialize display string for the new search45 outputLabel.Text = "Portions of array searched\n";46 47 // perform the binary search48 int element = BinarySearch( a, searchKey );49 50 if ( element != -1 )51 displayLabel.Text = "Found value in element " +52 element;53 else54 displayLabel.Text = "Value not found";55 56 } // end findButton_Click57 58 // searchs array for specified key59 public int BinarySearch( int[] array, int key )60 {61 int low = 0; // low subscript62 int high = array.Length - 1; // high subscript63 int middle; // middle subscript64 65 while ( low high )93 outputLabel.Text += " ";94 95 // mark middle element in output96 else if ( i == mid )97 outputLabel.Text += 98 array[ i ].ToString( "00" ) + "* ";If the middle element matches the search key, return the index of the middle elementIf the key value is smaller then the middle element, set the high index to be one less then the current middle indexOtherwise, set the low index to be one more then the middle indexOutput all elements of the array within two indices and mark the middle element. Print spaces for the other elements28BinarySearchTest.cs Program Output99 else100 outputLabel.Text += 101 array[ i ].ToString( "00" ) + " ";102 }103 104 outputLabel.Text += "\n";105 106 } // end BuildOutput107 108 } // end class BinarySearchTest29BinarySearchTest.cs Program Output30Tìm kiếm: Linear Search and Binary SearchTìm phần tử lớn nhất / nhỏ nhấtint tim_max(){ int i, max; max = mang_nguyen[0]; // phần tử đầu tiên for (i = 0; i mang_nguyen[i]) // nêu gap phân t nh hơn min = mang_nguyen[i]; } return min;}32Tìm kiếm: Linear Search and Binary SearchTìm phần tử có giá trị được cung cấpprivate void tim_kiem(int so_tim){ // Khai báo và tạo giá trị mặc định: giả sử không tìm thấy string kq = "Không tìm thấy " + so_tim + " trong mảng"; for (int i = 0; i = new ArrayList();Ý nghĩanew: khi tạo đối tượng ArrayListChú ý: trước khi sử dụng ArrayList, cần phải thêm vào reference System.CollectionsVí dụ ArrayList Danh_sach = new ArrayList();42Danh sách mảng3. Các xử lý trên danh sáchThêm một phần tử Danh_sach.Add();Ví dụ43Danh sách mảng3. Các xử lý trên danh sáchThêm danh sách các phần tử Danh_sach.AddRange();Ví dụ44Danh sách mảng3. Các xử lý trên danh sáchXóa một phần tử Danh_sach.RemoveAt(Vị trí);Ví dụ45Danh sách mảng3. Các xử lý trên danh sáchXoá tất cả các phần tử Danh_sach.Clear();Ví dụ46Danh sách mảng3. Các xử lý trên danh sáchTruy xuất phần tử tại vị trí i Danh_sach[i] Ví dụ47Danh sách mảng3. Các xử lý trên danh sáchLấy tổng số lượng phần tử trong danh sách Danh_sach.CountVí dụ48Danh sách mảng3. Các xử lý trên danh sáchTạo bản sao từ danh sách đã có =Danh_sach.Clone();Ví dụ49Danh sách mảng3. Các xử lý trên danh sáchSắp xếp (tăng dân) Danh_sach.Sort();Đảo ngược các phần tử trong danh sách Danh_sach.Reverse();50Danh sách mảng3. Các xử lý trên danh sáchTìm một phần tử Danh_sach.IndexOf();Trả về số >=0: Vị trí được tìm thấyTrả về số ,[Phân biệt hoa/thường]);Trả về số >=0: Vị trí được tìm thấyTrả về số [ , ] = new [ , ]Khởi gán mảng hai chiều chữ nhật:int[ , ] b = { { 1, 2 }, { 3, 4 } }58Truy xuất phần tử của mảng hai chiều chữ nhậtCú pháp [ i , j ] trong đó i là chỉ số dòng, j là chỉ số cộtVí dụ :X=A[4,5];static void PrintArray(int[,] a) { Console.WriteLine(); for (int i = 0; i [ ] [ ] - Khởi tạo mảng jagged: = new [số dòng của mảng ] [ ];Trong quá trình nhập giá trị số dòng cho mảng chúng ta sẽ nhập số cột tương ứng cho mỗi dòng.int[][] jagged = { new int[] { 1, 2 }, new int[] { 3 }, new int[] { 4, 5, 6 } };int[][] c;c = new int[ 2 ][ ]; // create 2 rowsc[ 0 ] = new int[ 5 ]; // create 5 columns for row 0c[ 1 ] = new int[ 3 ]; // create 3 columns for row 161TwoDimensionalArrays.cs1 // Fig. 7.14: TwoDimensionalArrays.cs2 // Initializing two-dimensional arrays.3 using System;4 using System.Drawing;5 using System.Collections;6 using System.ComponentModel;7 using System.Windows.Forms;8 using System.Data;9 10 public class TwoDimensionalArrays : System.Windows.Forms.Form11 {12 private System.Windows.Forms.Button showOutputButton;13 private System.Windows.Forms.Label outputLabel;14 15 // Visual Studio .NET generated code16 17 [STAThread]18 static void Main() 19 {20 Application.Run( new TwoDimensionalArrays() );21 }22 23 private void showOutputButton_Click( object sender, 24 System.EventArgs e )25 {26 // declaration and initialization of rectangular array27 int[,] array1 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };28 29 // declaration and initialization of jagged array30 int[][] array2 = new int[ 3 ][];31 array2[ 0 ] = new int[] { 1, 2 };32 array2[ 1 ] = new int[] { 3 };33 array2[ 2 ] = new int[] { 4, 5, 6 };34 35 outputLabel.Text += "Values in array1 by row are\n";Declare and initialize a rectangular integer array named array1Declare a jagged array named array2 with 3 rowsInitialize the first element in array2 to be an array that contains two integersInitialize the second element in array2 to be an array that contains 1 integerInitialize the third element in array2 to be an array that contains 3 integers62TwoDimensionalArrays.cs Program Output36 37 // output values in array138 for ( int i = 0; i highGrade )88 highGrade = grades[ i ][ j ];89 90 return highGrade;91 }92 Examine each element in grades arrayIf the current array element is less then the lowest grade, set the value of lowGrade to be the current elementExamine each element in grades arrayIf the current array element higher then the highest grade, set the value of highGrade to be the current element66DoubleArray.cs Program Output93 // determine average grade for a particular student94 public double Average( int[] setOfGrades )95 {96 int total = 0;97 98 for ( int i = 0; i TKey: kiểu dữ liệu của keyTValue: kiểu dữ liệu của value79Constructors của "Dictionary" Generic 80Phương thức của "Dictionary" Generic 81Thuộc tính của "Dictionary" Generic 82Ví dụ "Dictionary" Generic83That’s about all for today!System.Collections NamespaceSystem.Collections.Generic NamespaceArrayList ClassHashtable ClassSortedList ClassDictionary Generic ClassThank you all for your attention and patient !
Tài liệu liên quan