排序算法之—珠排序

具体的BeadSort的过程见:https://www.cnblogs.com/kkun/archive/2011/11/23/2260301.html

具体的代码实现:

// C++ program to implement gravity/bead sort 
#include <iostream>
#include <cstring>
using namespace std; 
  
#define BEAD(i, j) beads[i * max + j] 
  
  
/*
3	:1	1	1 				3:	1	1	1	1	1
5	:1	1	1	1	1   ==> 5:	1	1	1
1	:1 						1:	1
*/
void beadSort(int *a, int len) 
{ 
    // Find the maximum element 
    int max = a[0]; 
    for (int i = 1; i < len; i++) 
        if (a[i] > max) 
           max = a[i]; 
  
    // allocating memory 
    unsigned char beads[max*len]; 
    memset(beads, 0, sizeof(beads)); 
  
    // mark the beads 
    for (int i = 0; i < len; i++) 
        for (int j = 0; j < a[i]; j++) 
            BEAD(i, j) = 1; 
  
    for (int j = 0; j < max; j++) 
    { 
        // count how many beads are on each col 
        int sum = 0; 
        for (int i = 0; i < len; i++) 
        { 
            sum += BEAD(i, j); 
            BEAD(i, j) = 0; 
        } 
  
        // Move beads up 
        for (int i = len - sum; i < len; i++) 
            BEAD(i, j) = 1; 
    } 
  
    // Put sorted values in array using beads 
    for (int i = 0; i < len; i++) 
    { 
        int j; 
        for (j = 0; j < max && BEAD(i, j); j++); 
  
        a[i] = j; 
    } 
} 

void show(int *a, int len)
{
    int i;
    for (i = 0; i < len; i++)
        cout << a[i] << "\n";
}

// driver function to test the algorithm 
int main() 
{ 
	int len;
    cout << "\nEnter the number of elements : ";

    cin >> len;

    int arr[len];

    cout << "\nEnter the unsorted elements : ";

    for (int i = 0; i < len; ++i)
    {
        cout << "\n";
        cin >> arr[i];
    }
    
    beadSort(arr, len); 
  
    cout << "Sorted array\n";
    show(arr, len); 
  
    return 0; 
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值