Selection Sort คืออัลกอริธึมการเรียงลำดับที่ค้นหาค่าต่ำสุดในอาร์เรย์สำหรับการวนซ้ำแต่ละครั้งของลูป จากนั้นค่าต่ำสุดนี้จะถูกสลับกับองค์ประกอบอาร์เรย์ปัจจุบัน มีการปฏิบัติตามขั้นตอนนี้จนกว่าจะจัดเรียงอาร์เรย์
โปรแกรมที่แสดงการเรียงลำดับการเลือกใน C# มีดังต่อไปนี้
ตัวอย่าง
using System;
public class Example {
static void Main(string[] args) {
int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };
int n = 10;
Console.WriteLine("Selection sort");
Console.Write("Initial array is: ");
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
int temp, smallest;
for (int i = 0; i < n - 1; i++) {
smallest = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[smallest]) {
smallest = j;
}
}
temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
}
Console.WriteLine();
Console.Write("Sorted array is: ");
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
}
} ผลลัพธ์
ผลลัพธ์ของโปรแกรมข้างต้นมีดังนี้
Selection sort Initial array is: 56 1 99 67 89 23 44 12 78 34 Sorted array is: 1 12 23 34 44 56 67 78 89 99
ตอนนี้ เรามาทำความเข้าใจโปรแกรมข้างต้นกัน
ขั้นแรก อาร์เรย์จะเริ่มต้นและพิมพ์ค่าโดยใช้ for loop ซึ่งสามารถเห็นได้ในข้อมูลโค้ดต่อไปนี้
int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };
int n = 10;
Console.WriteLine("Selection sort");
Console.Write("Initial array is: ");
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
} nested for loop ใช้สำหรับกระบวนการเรียงลำดับตามจริง ในแต่ละรอบของ outer for loop จะพบองค์ประกอบที่เล็กที่สุดในอาร์เรย์และแทนที่ด้วยองค์ประกอบปัจจุบัน กระบวนการนี้จะดำเนินต่อไปจนกว่าจะจัดเรียงอาร์เรย์ ซึ่งสามารถเห็นได้ในข้อมูลโค้ดต่อไปนี้
for (int i = 0; i < n - 1; i++) {
smallest = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[smallest]) {
smallest = j;
}
}
temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
} ในที่สุดอาร์เรย์ที่เรียงลำดับจะปรากฏขึ้น ซึ่งสามารถเห็นได้ในข้อมูลโค้ดต่อไปนี้
Console.Write("Sorted array is: ");
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}