Bang hộiTiền mặt: 0 Xu Trò chơiHộp quà giáng sinhChủ Nhật, 17:11:44 - 30/06/2024
Chia sẻ kiến thức ngôn ngữ lập trình C, C++, C#, Java, Python, PHP, JS, SQL ...

Các điều hành viên: Mod, SMod, Admin

[C++] Các thuật toán sắp xếp cơ bản thường sử dụng

Re: [C++] Các thuật toán sắp xếp cơ bản thường sử dụng

#3 » Gửi bài gửi bởi nghiammo1992 » 12/09/2021 12:34 » @523438

Thuật toán Counting Sort – Thuật toán sắp xếp đếm phân phối (thuật toán tốt hơn Quick Sort, nhưng tốn bộ nhớ hơn)

Mã: Chọn tất cả
#include <iostream>


using namespace std;


// Function that sort the given input
void counting_sort(int input[], int n)
{

    
int output[n]; // The output will have sorted input array
    
int max input[0];
    
int min input[0];

    for(
int i 1ni++)
    {
        if(
input[i] > max)
            
max input[i]; // Maximum value in array
        
else if(input[i] < min)
            
min input[i]; // Minimum value in array
    
}

    
int k max min 1// Size of count array

    
int count_array[k]; // Create a count_array to store count of each individual input value
    
fill_n(count_arrayk0); // Initialize count_array elements as zero

    
for(int i 0ni++)
        
count_array[input[i] - min]++; // Store count of each individual input value

    /* Change count_array so that count_array now contains actual
     position of input values in output array */
    
for(int i 1ki++)
        
count_array[i] += count_array[1];


    
// Populate output array using count_array and input array
    
for(int i 0ni++)
    {
        
output[count_array[input[i] - min] - 1] = input[i];
        
count_array[input[i] - min]--;
    }


    for(
int i 0ni++)
        
input[i] = output[i]; // Copy the output array to input, so that input now contains sorted values

}


int main()
{

    
int arr[] {32,71,12,45,26,80,53,33,-7,99,1,5,2,-3,-100};

    
int n sizeof(arr) / sizeof(arr[0]); // so luong phan tu trong mang

    
counting_sort(arrn);

    
cout << "So luong phan tu trong mang: " << << endl;

    for (
int i arr) {
        
cout << << " ";
    }

    return 
0;
}

 
nghiammo1992
Hình đại diện của thành viên
Rank: ☀️2/30☀️
Cấp độ:
Tu luyện:
Like:
Online:
Bang hội: Tiếu Ngạo
Xếp hạng Bang hội: ⚡5/60⚡
Level:
Chủ đề đã tạo: 🩸4141/4141🩸
Tiền mặt:
Ngân hàng:
Nhóm:
Danh hiệu: ⚝Truyền Thuyết⚝
Giới tính:
Ngày tham gia:
Đến từ:
Thiết bị:
Số điện thoại:
(Google Chrome 94.0.460)

- Chia sẻ bài viết:

- Xem full chủ đề: http://chiase123.com/viewtopic.html?t=38279

- Link bài viết: http://chiase123.com/topic38279-2.html#p523438

Quay về C, C++, C#, Java, Python, PHP, JS, SQL ...