Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การเรียงลำดับการแทรกใน C #


Insertion Sort คืออัลกอริธึมการเรียงลำดับที่นำองค์ประกอบในแต่ละครั้งและแทรกในตำแหน่งที่ถูกต้องในอาร์เรย์ กระบวนการนี้จะดำเนินต่อไปจนกว่าจะจัดเรียงอาร์เรย์

โปรแกรมที่แสดงการเรียงลำดับการแทรกใน C# มีดังต่อไปนี้

ตัวอย่าง

using System;
namespace InsertionSortDemo {
   class Example {
      static void Main(string[] args) {
         int[] arr = new int[10] { 23, 9, 85, 12, 99, 34, 60, 15, 100, 1 };
         int n = 10, i, j, val, flag;
         Console.WriteLine("Insertion Sort");
         Console.Write("Initial array is: ");
         for (i = 0; i < n; i++) {
            Console.Write(arr[i] + " ");
         }
         for (i = 1; i < n; i++) {
            val = arr[i];
            flag = 0;
            for (j = i - 1; j >= 0 && flag != 1; ) {
               if (val < arr[j]) {
                  arr[j + 1] = arr[j];
                  j--;
                  arr[j + 1] = val;
               }
               else flag = 1;
            }
         }
         Console.Write("\nSorted Array is: ");
         for (i = 0; i < n; i++) {
            Console.Write(arr[i] + " ");
         }
      }
   }
}

ผลลัพธ์

ผลลัพธ์ของโปรแกรมข้างต้นมีดังนี้

Insertion Sort
Initial array is: 23 9 85 12 99 34 60 15 100 1
Sorted Array is: 1 9 12 15 23 34 60 85 99 100

ตอนนี้ เรามาทำความเข้าใจโปรแกรมข้างต้นกัน

ขั้นแรก อาร์เรย์จะเริ่มต้นและพิมพ์ค่าโดยใช้ for loop สามารถเห็นได้ในข้อมูลโค้ดต่อไปนี้ -

int[] arr = new int[10] { 23, 9, 85, 12, 99, 34, 60, 15, 100, 1 };
int n = 10, i, j, val, flag;
Console.WriteLine("Insertion Sort");
Console.Write("Initial array is: ");
for (i = 0; i < n; i++) {
   Console.Write(arr[i] + " ");
}

nested for loop ใช้สำหรับกระบวนการเรียงลำดับตามจริง ในแต่ละรอบของ outer for loop องค์ประกอบปัจจุบันจะถูกแทรกลงในตำแหน่งที่ถูกต้องในอาร์เรย์ กระบวนการนี้จะดำเนินต่อไปจนกว่าจะจัดเรียงอาร์เรย์ ซึ่งสามารถเห็นได้ในข้อมูลโค้ดต่อไปนี้

for (i = 1; i < n; i++) {
   val = arr[i];
   flag = 0;
   for (j = i - 1; j >= 0 && flag != 1; ) {
      if (val < arr[j]) {
         arr[j + 1] = arr[j];
         j--;
         arr[j + 1] = val;
      } else flag = 1;
   }
}

ในที่สุดอาร์เรย์ที่เรียงลำดับจะปรากฏขึ้น ซึ่งสามารถเห็นได้ในข้อมูลโค้ดต่อไปนี้

Console.Write("\nSorted Array is: ");
for (i = 0; i < n; i++) {
   Console.Write(arr[i] + " ");
}