อาร์เรย์คือกลุ่มของข้อมูลที่เกี่ยวข้องกัน จัดเก็บภายใต้ชื่อเดียว
ตัวอย่าง: int student[30];
ที่นี่ student เป็นชื่ออาร์เรย์ที่เก็บข้อมูล 30 รายการ ด้วยชื่อตัวแปรเดียว
การดำเนินการ
การดำเนินการของอาร์เรย์อธิบายดังนี้:
การค้นหา (Searching) - ใช้หาว่าองค์ประกอบเฉพาะมีอยู่หรือไม่
การเรียงลำดับ (Sorting) - ช่วยจัดเรียงองค์ประกอบในอาร์เรย์จากน้อยไปมากหรือมากไปน้อย
การเดินทาง (Traversing) - ประมวลผลทุกองค์ประกอบในอาร์เรย์ตามลำดับ
การแทรก (Inserting) - ช่วยแทรกองค์ประกอบในอาร์เรย์
การลบ (Deleting) - ช่วยลบองค์ประกอบในอาร์เรย์
ในโปรแกรมนี้ เราใช้เทคนิคการสลับ (Swapping) เพื่อเรียงลำดับองค์ประกอบจากน้อยไปมาก
ตรรกะที่ใช้ เรียงลำดับอาร์เรย์จากน้อยไปมาก ดังนี้:
for(i = 0; i < 10 - 1; i++) {
for(j = i + 1; j < 10; j++) {
if(element[i] > element[j]) {
temp = element[i]; // สลับ element[i] กับ element[j]
element[i] = element[j];
element[j] = temp;
}
}
}โปรแกรม
โปรแกรม C เรียงลำดับอาร์เรย์ 10 องค์ประกอบจากน้อยไปมาก:
#include <stdio.h>
int main() {
int element[10], i, j, temp;
printf("enter 10 integer numbers:");
for(i = 0; i < 10; i++) {
scanf("%d", &element[i]);
}
for(i = 0; i < 10 - 1; i++) {
for(j = i + 1; j < 10; j++) {
if(element[i] > element[j]) {
temp = element[i]; // สลับ element[i] กับ element[j]
element[i] = element[j];
element[j] = temp;
}
}
}
printf("Elements are now in ascending order:");
for(i = 0; i < 10; i++)
printf("%d\n", element[i]);
return 0;
}ผลลัพธ์
ผลลัพธ์ด้านล่าง:
enter 10 integer numbers: 12 23 34 1 22 34 56 45 33 78 Elements are now in ascending order: 1 12 22 23 33 34 34 45 56 78