首页 > 其他分享 >并行计算排序

并行计算排序

时间:2024-05-22 16:54:36浏览次数:19  
标签:std end int start 并行计算 score array 排序

#include <iostream>
#include <vector>
#include <chrono>
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <omp.h> 

// Structure to hold data
struct Data {
    int id;
    int age;
    float weight;
    float height; // Additional attribute
    std::string name;
    std::string address;
    std::string email;
    std::string phone;
    std::string city;
    std::string country;
    int salary;
    int years_of_experience; // Additional attribute
    bool employed; // Additional attribute
    float rating; // Additional attribute
    float score; // Additional attribute
};
  
int Partition(std::vector<Data>& data, int start, int end) {  
    Data temp = data[start]; // 以第一个元素为基准  
    int pivot = start;  
    while (start < end) {  
        while (start < end && data[end].score >= temp.score) end--; // 找到第一个比score小的位置 
        if (start < end) {  
            data[start] = data[end]; // 交换整个对象  
        }   
        while (start < end && data[start].score <= temp.score) start++; // 找到第一个比score大的数的位置  
        if (start < end) {  
            data[end] = data[start]; // 交换整个对象  
        }  
    }  
    data[start] = temp; // 将基准放到正确的位置  
    return start;  
}  
  
void quickSort(std::vector<Data>& data, int start, int end) {  
    if (start < end) {  
        int pos = Partition(data, start, end);  
    #pragma omp parallel sections    //设置并行区域
        {
            #pragma omp section          //该区域对前部分数据进行排序
            quickSort(data, start, pos - 1);
            #pragma omp section          //该区域对后部分数据进行排序
            quickSort(data, pos + 1, end);
        }
    }
}


// Compare function for std::sort by score
bool compare_score(const Data& a, const Data& b) {
    return a.score < b.score;
}

// Validation function to check if the array is sorted correctly by score
bool validate_score(const std::vector<Data>& array) {
    for (size_t i = 1; i < array.size(); i++) {
        if (array[i].score < array[i - 1].score)
            return false; // Array is not sorted correctly
    }
    return true; // Array is sorted correctly
}

int main(int argc, char *argv[]) {
    if (argc != 2 && argc != 3) {
        std::cout << "Usage: " << argv[0] << " <array_size>" << std::endl;
        return 1;
    }
    
    int n =1;
    if(argc ==3 ) n = atoi(argv[2]);
    
    
    uint64_t array_size = std::strtoull(argv[1], nullptr, 10);
    if (array_size == 0) {
        std::cout << "Array size must be a positive integer" << std::endl;
        return 1;
    }

    std::vector<Data> array(array_size);

    // Initialize data
    srand(time(NULL)); // Seed the random number generator
    for (uint64_t i = 0; i < array_size; i++) {
        array[i].id = i + 1;
        array[i].age = rand() % 100 + 1; // Random age between 1 and 100
        array[i].weight = static_cast<float>(rand()) / RAND_MAX * 100.0f; // Random weight between 0 and 100
        array[i].height = static_cast<float>(rand()) / RAND_MAX * 200.0f; // Random height between 0 and 200
        array[i].name = "Name" + std::to_string(i);
        array[i].address = "Address" + std::to_string(i);
        array[i].email = "Email" + std::to_string(i) + "@example.com";
        array[i].phone = "+1234567890" + std::to_string(i);
        array[i].city = "City" + std::to_string(i);
        array[i].country = "Country" + std::to_string(i);
        array[i].years_of_experience = rand() % 30; // Random years of experience between 0 and 29
        array[i].employed = rand() % 2; // Random employed status (0 or 1)
        array[i].rating = static_cast<float>(rand()) / RAND_MAX * 5.0f; // Random rating between 0 and 5
        array[i].score = static_cast<float>(rand()) / RAND_MAX * 11000000.0f - 1000000.0f; // Random score between -1000000 and 10000000
    }

    // Start timer
    auto start_time = std::chrono::high_resolution_clock::now();

    // Sort the array using std::sort by score
    //   std::sort(array.begin(), array.end(), compare_score);
    
    if(argc == 2){
    	 std::sort(array.begin(), array.end(), compare_score);
	} 
    else{
    omp_set_num_threads(n);  // 设置线程数
    quickSort(array, 0, array_size-1);  
}
    // End timer
    auto end_time = std::chrono::high_resolution_clock::now();
    double time_spent = std::chrono::duration_cast<std::chrono::duration<double>>(end_time - start_time).count();

    // Print time taken
    std::cout << "Time taken: " << time_spent << " seconds" << std::endl;

    //// Print the top ten results
    //std::cout << "Top ten results:" << std::endl;
    //for (int i = 0; i < std::min(10, static_cast<int>(array.size())); ++i) {
    //    std::cout << "ID: " << array[i].id << ", Age: " << array[i].age << ", Weight: " << array[i].weight 
    //              << ", Score: " << array[i].score << std::endl;
    //    // Print other attributes as needed
    //}

    //// Print the last ten results
    //std::cout << "Last ten results:" << std::endl;
    //int start_index = std::max(0, static_cast<int>(array.size()) - 10);
    //for (int i = start_index; i < array.size(); ++i) {
    //    std::cout << "ID: " << array[i].id << ", Age: " << array[i].age << ", Weight: " << array[i].weight 
    //              << ", Score: " << array[i].score << std::endl;
    //    // Print other attributes as needed
    //}

    // Validate if the array is sorted correctly by score
    if (validate_score(array))
        std::cout << "Validation: Array is sorted correctly by score" << std::endl;
    else
        std::cout << "Validation: Array is not sorted correctly by score" << std::endl;

    return 0;
}

标签:std,end,int,start,并行计算,score,array,排序
From: https://www.cnblogs.com/MisakaAzusa/p/18206629

相关文章

  • 逗号分开的字符串,统计个数从高到底排序
    usesWinapi.Windows,Winapi.Messages,System.SysUtils,System.Variants,System.Classes,Vcl.Graphics,System.RegularExpressions, functionCompareStrings(List:TStringList;Index1,Index2:Integer):Integer;beginResult:=StrToInt(List.ValueF......
  • NumPy 数组排序、过滤与随机数生成详解
    NumPy数组排序排序数组排序数组意味着将元素按特定顺序排列。顺序可以是数字大小、字母顺序、升序或降序等。NumPy的ndarray对象提供了一个名为sort()的函数,用于对数组进行排序。示例:importnumpyasnparr=np.array([3,2,0,1])print(np.sort(arr))输出:[0......
  • mybatis中进行value的排序无效
    原因是:在MySQL中,如果value是一个字符串,那么在ORDERBY语句中进行降序排序时,MySQL会根据字符串的字典顺序来排序,而不是数值大小。这意味着字符串会按照首字符的ASCII值进行比较,例如,"100"会排在"2"前面,因为在ASCII码中,"1"的值小于"2"的值。解决:可以在mybatis中进行value的类型修改;......
  • [转] 整理一下SQLSERVER的排序规则
    原文链接:https://www.cnblogs.com/JimZhang/archive/2006/04/03/365573.htmlSQLSERVER的排序规则平时使用不是很多,也许不少初学者还比较陌生,但有一个错误大家应是经常碰到:SQLSERVER数据库,在跨库多表连接查询时,若两数据库默认字符集不同,系统就会返回这样的错误:“无法解决eq......
  • 常见的排序算法——归并排序(四)
    本文记述了针对归并排序的3项改进和一份参考实现代码,并在说明了算法的性能后用随机数据进行了验证。◆思想本文实现了《算法(第4版)》书中提到的2项改进和练习题2.2.10。对小规模子数组使用插入排序。因为递归会使小规模问题中方法的调用过于频繁,所以改进对它们的处理方法......
  • 3、Oracle 中的过滤、排序
    最近项目要用到Oracle,奈何之前没有使用过,所以在B站上面找了一个学习视频,用于记录学习过程以及自己的思考。视频链接:【尚硅谷】Oracle数据库全套教程,oracle从安装到实战应用如果有侵权,请联系删除,谢谢。更加详细的教程,可以直接观看此链接Oracle教程1、过滤1.1、基本使用方式......
  • Junit5的使用:排序注释
    packagecom.test.api.junit;importorg.junit.jupiter.api.*;importorg.junit.jupiter.params.ParameterizedTest;importorg.junit.jupiter.params.provider.CsvFileSource;importorg.junit.jupiter.params.provider.CsvSource;importorg.junit.jupiter.params.provider.......
  • 动态排序
    usingDynamicSort;usingMicrosoft.EntityFrameworkCore;List<StudnetEntity>studentList=newList<StudnetEntity>(){newStudnetEntity(){Name="Chen",Age=28},newStudnetEntity(){Name="Wang",Age=29}};......
  • python算法:详细图解: 排序:冒泡排序
    一,什么是冒泡排序?1,冒泡排序和快速排序都属于交换排序所谓交换,就是对序列中两个元素根据键值的比较结果来对换这两个记录在序列中的位置交换排序的特点:将键值较大的元素向序列的尾部移动,键值较小的元素向序列的前部移动2,冒泡排序:BubbleSort,是一种最基础的交换排序,冒泡排......
  • 聊聊MySQL是如何处理排序的
    本文分享自华为云社区《MySQL怎样处理排序⭐️如何优化需要排序的查询?》,作者:菜菜的后端私房菜。前言在MySQL的查询中常常会用到 orderby 和 groupby 这两个关键字它们的相同点是都会对字段进行排序,那查询语句中的排序是如何实现的呢?当使用的查询语句需要进行排序时有两种......