Sắp xếp mảng


Bài tập 1:Sử dụng thuật toán sắp xếp nổi bọt (bubble sort) viết chương trình C# để sắp xếp một mảng 10 phần tử theo thứ tự tăng dần.

Giải pháp:


class Program
{
    static void Main(string[] args)
    {
        int[] arr = new int[10] { 23, 2, 3, 34, 6,1,24,45,78,8}; //tập dữ liệu chưa sắp xếp
        bubblesort(arr, 10); //gọi thủ tục sắp xếp nổi bọt
        int i;
        for (i = 0; i < 10; i++)
        Console.Write(arr[i] + "\t"); //in ra kết quả theo thứ tự tăng dần
        Console.ReadLine();
    }
    ///Thuật toán nổi bọt
    static void bubblesort(int[] dataset, int n)
    {
    int i, j;
    for (i = 0; i < n; i++) 
      for (j = n - 1; j > i; j--)
       if (dataset[j] < dataset[j - 1])
        {
          int temp = dataset[j];
          dataset[j] = dataset[j - 1];
          dataset[j - 1] = temp;
        }
  }
}

Bài tập 2: Chỉnh sửa code C# ở bài tập 1 để thực hiện sắp xếp mảng theo thứ tự giảm dần.

Giải pháp:


class Program
{
    static void Main(string[] args)
    {
        int[] arr = new int[10] { 23, 2, 3, 34, 6,1,24,45,78,8}; //tập dữ liệu chưa sắp xếp
        bubblesort(arr, 10); //gọi thủ tục sắp xếp nổi bọt
        int i;
        for (i = 0; i < 10; i++)
        Console.Write(arr[i] + "\t"); //in ra kết quả theo thứ tự giảm dần
        Console.ReadLine();
    }
    ///Thuật toán nổi bọt
    static void bubblesort(int[] dataset, int n)
    {
    int i, j;
    for (i = 0; i < n; i++) 
     for (j = n - 1; j > i; j--)
       if (dataset[j] > dataset[j - 1])
        {
          int temp = dataset[j];
          dataset[j] = dataset[j - 1];
          dataset[j - 1] = temp;
        }
  }
}

Có thể bạn sẽ thích…

Trả lời

EnglishVietnamese