CUDA加速排序

#include<iostream>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include<stdio.h>
#include<memory>
#include<cuda.h>
#define arraySize 10
#define threadPerBlock 5

__global__ void addKernel(int* d_a, int* d_b) {
	int count = 0;
	int tid = threadIdx.x;
	int ttid = blockIdx.x * threadPerBlock + tid;
	int val = d_a[ttid];

	__shared__ int cache[threadPerBlock];

	for (int i = tid; i < arraySize; i += threadPerBlock) {
		cache[tid] = d_a[i];
		__syncthreads();
		for (int j = 0; j < threadPerBlock; ++j)
		{
			if (val > cache[j]) {
				count++;
				__syncthreads();
			}
		}
	}
	d_b[count] = val;
}

int main() {
	int h_a[arraySize] = { 5, 9, 3, 4, 8, 10, 7, 1, 2, 6};
	int h_b[arraySize];
	int* d_a, * d_b;

	cudaMalloc((void**)&d_a, arraySize * sizeof(int));
	cudaMalloc((void**)&d_b, arraySize * sizeof(int));

	cudaMemcpy(d_a, h_a, arraySize * sizeof(int), cudaMemcpyHostToDevice);

	addKernel << <arraySize / threadPerBlock, threadPerBlock >> > (d_a, d_b);

	cudaDeviceSynchronize();

	cudaMemcpy(h_b, d_b, arraySize * sizeof(int), cudaMemcpyDeviceToHost);
	printf("The Enumeration sorted Array is: \n");

	for (int i = 0; i < arraySize; i++)
	{
		printf("%d\t", h_b[i]);
	}

	cudaFree(d_a);
	cudaFree(d_b);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值