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

โปรแกรม Bubble Sort ใน C#

Bubble Sort คืออัลกอริทึมจัดเรียงง่ายๆ เปรียบเทียบคู่ที่อยู่ติดกัน สลับที่ถ้าอยู่ผิดลำดับ

ตัวอย่างขั้นตอน (Array: 78, 55, 45, 98, 13)

รอบที่ 1: 78↔55 → 55,78,45,98,13 → 78↔45 → 55,45,78,98,13 → 98>78 ไม่สลับ → 98↔13 → 55,45,78,13,98

ทำซ้ำจนเรียบร้อย → 13, 45, 55, 78, 98

ตัวอย่างโค้ดเต็ม

using System;
namespace BubbleSort {
    class MySort {
        static void Main(string[] args) {
            int[] arr = { 78, 55, 45, 98, 13 };
            int temp;
            for (int j = 0; j <= arr.Length - 2; j++) {
                for (int i = 0; i <= arr.Length - 2; i++) {
                    if (arr[i] > arr[i + 1]) {
                        temp = arr[i + 1];
                        arr[i + 1] = arr[i];
                        arr[i] = temp;
                    }
                }
            }
            Console.WriteLine("Sorted:");
            foreach (int p in arr) Console.Write(p + " ");
            Console.Read();
        }
    }
}

ผลลัพธ์

Sorted: 13 45 55 78 98

Complexity: Time O(n²), Space O(1) - เหมาะสำหรับข้อมูลเล็กหรือ Nearly sorted

การเพิ่มประสิทธิภาพ: เพิ่ม flag ตรวจสอบว่ามีการ swap ในรอบนั้นไหม ถ้าไม่มี = เรียบร้อยแล้ว