陣列資料結構



什麼是陣列?

陣列是一種線性資料結構,定義為一組具有相同或不同資料型別的元素的集合。它們存在於單維度和多維度中。當需要將多個類似性質的元素儲存在一個地方時,這些資料結構就會出現。

Array

陣列索引和記憶體地址的區別在於,陣列索引充當標記陣列中元素的鍵值。但是,記憶體地址是可用空閒記憶體的起始地址。

以下是瞭解陣列概念的重要術語。

  • 元素 - 儲存在陣列中的每個專案都稱為元素。

  • 索引 - 陣列中每個元素的位置都有一個數字索引,用於識別該元素。

語法

CC++程式語言中建立陣列 -

data_type array_name[array_size]={elements separated by commas}
or,
data_type array_name[array_size];

Java程式語言中建立陣列 -

data_type[] array_name = {elements separated by commas}
or,
data_type array_name = new data_type[array_size];

陣列的必要性

陣列被用作從小型排序問題到更復雜問題(如旅行推銷員問題)的許多問題的解決方案。除了陣列之外,還有許多其他資料結構為這些問題提供了高效的時間和空間複雜度,那麼是什麼使使用陣列變得更好呢?答案在於隨機訪問查詢時間。

陣列提供O(1)隨機訪問查詢時間。這意味著訪問陣列的第1個索引和陣列的第1000個索引將花費相同的時間。這是因為陣列帶有一個指標和一個偏移量值。指標指向記憶體的正確位置,偏移量值顯示在所述記憶體中查詢多遠。

                           array_name[index]
                              |       |
                           Pointer   Offset

因此,在一個包含6個元素的陣列中,要訪問第一個元素,陣列將指向第0個索引。類似地,要訪問第6個元素,陣列將指向第5個索引。

陣列表示

陣列表示為一組桶,每個桶儲存一個元素。這些桶從'0'到'n-1'索引,其中n是該特定陣列的大小。例如,大小為10的陣列將具有從0到9索引的桶。

此索引對於多維陣列也將類似。如果它是二維陣列,則每個桶中將有子桶。然後它將被索引為array_name[m][n],其中m和n是陣列中每個級別的尺寸。

Array Representation

根據以上說明,以下是要考慮的重要事項。

  • 索引從0開始。

  • 陣列長度為9,這意味著它可以儲存9個元素。

  • 每個元素都可以透過其索引訪問。例如,我們可以獲取索引為6的元素作為23。

陣列的基本操作

陣列的基本操作包括插入、刪除、搜尋、顯示、遍歷和更新。這些操作通常用於修改陣列中的資料或報告陣列的狀態。

以下是陣列支援的基本操作。

  • 遍歷 - 一次列印所有陣列元素。

  • 插入 - 在給定索引處新增一個元素。

  • 刪除 - 刪除給定索引處的元素。

  • 搜尋 - 使用給定索引或值搜尋元素。

  • 更新 - 更新給定索引處的元素。

  • 顯示 - 顯示陣列的內容。

在C中,當陣列初始化為指定大小後,它會按照以下順序為其元素分配預設值。

資料型別 預設值
bool false
char 0
int 0
float 0.0
double 0.0f
void
wchar_t 0

陣列 - 插入操作

在插入操作中,我們將一個或多個元素新增到陣列中。根據需要,可以在陣列的開頭、結尾或任何給定索引處新增新元素。這是使用程式語言的輸入語句完成的。

演算法

以下是線上性陣列中插入元素的演算法,直到我們到達陣列的末尾 -

1. Start
2. Create an Array of a desired datatype and size.
3. Initialize a variable 'i' as 0.
4. Enter the element at ith index of the array.
5. Increment i by 1.
6. Repeat Steps 4 & 5 until the end of the array.
7. Stop

示例

在這裡,我們看到了插入操作的實際實現,我們將在陣列末尾新增資料 -

#include <stdio.h>
int main(){
   int LA[3] = {}, i;
   printf("Array Before Insertion:\n");
   for(i = 0; i < 3; i++)
      printf("LA[%d] = %d \n", i, LA[i]);
   printf("Inserting Elements.. \n");
   printf("The array elements after insertion :\n"); // prints array values
   for(i = 0; i < 3; i++) {
      LA[i] = i + 2;
      printf("LA[%d] = %d \n", i, LA[i]);
   }
   return 0;
}
#include <iostream>
using namespace std;
int main(){
   int LA[3] = {}, i;
   cout << "Array Before Insertion:" << endl;
   for(i = 0; i < 3; i++)
      cout << "LA[" << i <<"] = " << LA[i] << endl; 
      
   //prints garbage values
   cout << "Inserting elements.." <<endl;
   cout << "Array After Insertion:" << endl; // prints array values
   for(i = 0; i < 5; i++) {
      LA[i] = i + 2;
      cout << "LA[" << i <<"] = " << LA[i] << endl;
   }
   return 0;
}
public class ArrayDemo {
   public static void main(String []args) {
      int LA[] = new int[3];
      System.out.println("Array Before Insertion:");
      for(int i = 0; i < 3; i++)
         System.out.println("LA[" + i + "] = " + LA[i]); //prints empty array
      System.out.println("Inserting Elements..");
      
      // Printing Array after Insertion
      System.out.println("Array After Insertion:");
      for(int i = 0; i < 3; i++) {
         LA[i] = i+3;
         System.out.println("LA[" + i + "] = " + LA[i]);
      }
   }
}
# python program to insert element using insert operation
def insert(arr, element):
	arr.append(element)
# Driver's code
if __name__ == '__main__':
	# declaring array and value to insert
	LA = [0, 0, 0]
	x = 0
	# array before inserting an element
	print("Array Before Insertion: ")
	for x in range(len(LA)):
	    print("LA", [x], " = " , LA[x])
	print("Inserting elements....")
	# array after Inserting element
	for x in range(len(LA)):
	    LA.append(x);
	    LA[x] = x+1;
	print("Array After Insertion: ")
	for x in range(len(LA)):
	    print("LA", [x], " = " , LA[x])

輸出

Array Before Insertion:
LA[0] = 0
LA[1] = 0
LA[2] = 0
Inserting elements..
Array After Insertion:
LA[0] = 2
LA[1] = 3
LA[2] = 4
LA[3] = 5
LA[4] = 6

對於陣列插入操作的其他變體,點選此處

陣列 - 刪除操作

在此陣列操作中,我們從陣列的特定索引中刪除一個元素。此刪除操作發生在我們為後續索引中的值分配給當前索引時。

演算法

假設LA是一個包含N個元素的線性陣列,K是一個正整數,使得K<=N。以下是刪除LA中第K個位置的元素的演算法。

1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set LA[J] = LA[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop

示例

以下是此操作在各種程式語言中的實現 -

#include <stdio.h>
void main(){
   int LA[] = {1,3,5};
   int n = 3;
   int i;
   printf("The original array elements are :\n");
   for(i = 0; i<n; i++)
      printf("LA[%d] = %d \n", i, LA[i]);
   for(i = 1; i<n; i++) {
      LA[i] = LA[i+1];
      n = n - 1;
   }
   printf("The array elements after deletion :\n");
   for(i = 0; i<n; i++)
      printf("LA[%d] = %d \n", i, LA[i]);
}
#include <iostream>
using namespace std;
int main(){
   int LA[] = {1,3,5};
   int i, n = 3;
   cout << "The original array elements are :"<<endl;
   for(i = 0; i<n; i++) {
      cout << "LA[" << i << "] = " << LA[i] << endl;
   }
   for(i = 1; i<n; i++) {
      LA[i] = LA[i+1];
      n = n - 1;
   }
   cout << "The array elements after deletion :"<<endl;
   for(i = 0; i<n; i++) {
      cout << "LA[" << i << "] = " << LA[i] <<endl;
   }
}
public class ArrayDemo {
   public static void main(String []args) {
      int LA[] = new int[3];
      int n = LA.length;
      System.out.println("Array Before Deletion:");
      for(int i = 0; i < n; i++) {
         LA[i] = i + 3;
         System.out.println("LA[" + i + "] = " + LA[i]);
      }
      for(int i = 1; i<n-1; i++) {
         LA[i] = LA[i+1];
         n = n - 1;
      }
      System.out.println("Array After Deletion:");
      for(int i = 0; i < n; i++) {
         System.out.println("LA[" + i + "] = " + LA[i]);
      }
   }
}
#python program to delete the value using delete operation
if __name__ == '__main__':
	# Declaring array and deleting value
	LA = [0,0,0]
	n = len(LA)
	print("Array Before Deletion: ")
	for x in range(len(LA)):
	    LA.append(x)
	    LA[x] = x + 3
	    print("LA", [x], " = " , LA[x])
	# delete the value if exists 
	# or show error it does not exist in the list 
	for x in range(1, n-1):
	    LA[x] = LA[x+1]
	    n = n-1
	print("Array After Deletion: ")
	for x in range(n):
	    print("LA", [x], " = " , LA[x])

輸出

The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
The array elements after deletion :
LA[0] = 1
LA[1] = 5

陣列 - 搜尋操作

使用鍵在陣列中搜索元素;鍵元素依次比較陣列中的每個值,以檢查鍵是否存在於陣列中。

演算法

假設LA是一個包含N個元素的線性陣列,K是一個正整數,使得K<=N。以下是使用順序搜尋查詢值為ITEM的元素的演算法。

1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF LA[J] is equal ITEM THEN GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop

示例

以下是此操作在各種程式語言中的實現 -

#include <stdio.h>
void main(){
   int LA[] = {1,3,5,7,8};
   int item = 5, n = 5;
   int i = 0, j = 0;
   printf("The original array elements are :\n");
   for(i = 0; i<n; i++) {
      printf("LA[%d] = %d \n", i, LA[i]);
   }
   for(i = 0; i<n; i++) {
      if( LA[i] == item ) {
         printf("Found element %d at position %d\n", item, i+1);
      }
   }
}
#include <iostream>
using namespace std;
int main(){
   int LA[] = {1,3,5,7,8};
   int item = 5, n = 5;
   int i = 0;
   cout << "The original array elements are : " <<endl;
   for(i = 0; i<n; i++) {
      cout << "LA[" << i << "] = " << LA[i] << endl;
   }
   for(i = 0; i<n; i++) {
      if( LA[i] == item ) {
         cout << "Found element " << item << " at position " << i+1 <<endl;
      }
   }
   return 0;
}
public class ArrayDemo{
   public static void main(String []args){
      int LA[] = new int[5];
      System.out.println("Array:");
      for(int i = 0; i < 5; i++) {
         LA[i] = i + 3;
         System.out.println("LA[" + i + "] = " + LA[i]);
      }
      for(int i = 0; i < 5; i++) {
         if(LA[i] == 6)
            System.out.println("Element " + 6 + " is found at index " + i);
      }
   }
}
#search operation using python
def findElement(arr, n, value):
	for i in range(n):
		if (arr[i] == value):
			return i
	# If the key is not found
	return -1
# Driver's code
if __name__ == '__main__':
	LA = [1,3,5,7,8]
	print("Array element are: ")
	for x in range(len(LA)):
	    print("LA", [x], " = ", LA[x])
	value = 5
	n = len(LA)
		# element found using search operation
	index = findElement(LA, n, value)
	if index != -1:
		print("Element", value, "Found at position = " + str(index + 1))
	else:
		print("Element not found")

輸出

The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
Found element 5 at position 3

陣列 - 遍歷操作

此操作遍歷陣列的所有元素。我們使用迴圈語句來執行此操作。

演算法

以下是遍歷線性陣列中所有元素的演算法 -

1  Start
2. Initialize an Array of certain size and datatype.
3. Initialize another variable ‘i’ with 0.
4. Print the ith value in the array and increment i.
5. Repeat Step 4 until the end of the array is reached.
6. End

示例

以下是此操作在各種程式語言中的實現 -

#include <stdio.h>
int main(){
   int LA[] = {1,3,5,7,8};
   int item = 10, k = 3, n = 5;
   int i = 0, j = n;
   printf("The original array elements are :\n");
   for(i = 0; i<n; i++) {
      printf("LA[%d] = %d \n", i, LA[i]);
   }
}
#include <iostream>
using namespace std;
int main(){
   int LA[] = {1,3,5,7,8};
   int item = 10, k = 3, n = 5;
   int i = 0, j = n;
   cout << "The original array elements are:\n";
   for(i = 0; i<n; i++)
      cout << "LA[" << i << "] = " << LA[i] << endl;
   return 0;
}
public class ArrayDemo {
   public static void main(String []args) {
      int LA[] = new int[5];
      System.out.println("The array elements are: ");
      for(int i = 0; i < 5; i++) {
         LA[i] = i + 2;
         System.out.println("LA[" + i + "] = " + LA[i]);
      }
   }
}
# Python code to iterate over a array using python
LA = [1, 3, 5, 7, 8]
# length of the elements
length = len(LA)
# Traversing the elements using For loop and range
# same as 'for x in range(len(array))'
print("Array elements are: ")
for x in range(length):
	print("LA", [x], " = ", LA[x])

輸出

The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8

陣列 - 更新操作

更新操作是指更新陣列中給定索引處的現有元素。

演算法

假設LA是一個包含N個元素的線性陣列,K是一個正整數,使得K<=N。以下是更新LA中第K個位置的元素的演算法。

1. Start
2. Set LA[K-1] = ITEM
3. Stop

示例

以下是此操作在各種程式語言中的實現 -

#include <stdio.h>
void main(){
   int LA[] = {1,3,5,7,8};
   int k = 3, n = 5, item = 10;
   int i, j;
   printf("The original array elements are :\n");
   for(i = 0; i<n; i++) {
      printf("LA[%d] = %d \n", i, LA[i]);
   }
   LA[k-1] = item;
   printf("The array elements after updation :\n");
   for(i = 0; i<n; i++) {
      printf("LA[%d] = %d \n", i, LA[i]);
   }
}
#include <iostream>
using namespace std;
int main(){
   int LA[] = {1,3,5,7,8};
   int item = 10, k = 3, n = 5;
   int i = 0, j = n;
   cout << "The original array elements are :\n";
   for(i = 0; i<n; i++)
      cout << "LA[" << i << "] = " << LA[i] << endl;
   LA[2] = item;
   cout << "The array elements after updation are :\n";
   for(i = 0; i<n; i++)
      cout << "LA[" << i << "] = " << LA[i] << endl;
   return 0;
}
public class ArrayDemo {
   public static void main(String []args) {
      int LA[] = new int[5];
      int item = 15;
      System.out.println("The array elements are: ");
      for(int i = 0; i < 5; i++) {
         LA[i] = i + 2;
         System.out.println("LA[" + i + "] = " + LA[i]);
      }
      LA[3] = item;
      System.out.println("The array elements after updation are: ");
      for(int i = 0; i < 5; i++)
         System.out.println("LA[" + i + "] = " + LA[i]);
   }
}
#update operation using python
#Declaring array elements
LA = [1,3,5,7,8]
#before updation
print("The original array elements are :");
for x in range(len(LA)):
    print("LA", [x], " = ", LA[x])
#after updation
LA[2] = 10
print("The array elements after updation are: ")
for x in range(len(LA)):
    print("LA", [x], " = ", LA[x])
 

輸出

The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after updation :
LA[0] = 1
LA[1] = 3
LA[2] = 10
LA[3] = 7
LA[4] = 8

陣列 - 顯示操作

此操作使用列印語句顯示整個陣列中的所有元素。

演算法

假設LA是一個包含N個元素的線性陣列。以下是顯示陣列元素的演算法。

1. Start
2. Print all the elements in the Array
3. Stop

示例

以下是此操作在各種程式語言中的實現 -

#include <stdio.h>
int main(){
   int LA[] = {1,3,5,7,8};
   int n = 5;
   int i;
   printf("The original array elements are :\n");
   for(i = 0; i<n; i++) {
      printf("LA[%d] = %d \n", i, LA[i]);
   }
}
#include <iostream>
using namespace std;
int main(){
   int LA[] = {1,3,5,7,8};
   int n = 5;
   int i;
   cout << "The original array elements are :\n";
   for(i = 0; i<n; i++)
      cout << "LA[" << i << "] = " << LA[i] << endl;
   return 0;
}
public class ArrayDemo {
   public static void main(String []args) {
      int LA[] = new int[5];
      System.out.println("The array elements are: ");
      for(int i = 0; i < 5; i++) {
         LA[i] = i + 2;
         System.out.println("LA[" + i + "] = " + LA[i]);
      }
   }
}
#Display operation using python
#Display operation using python
#Declaring array elements
LA = [2,3,4,5,6]
#Displaying the array
print("The array elements are: ")
for x in range(len(LA)):
    print("LA", [x], " = " , LA[x])
 

輸出

The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
廣告