Question: help check and correct my program #include #include #include #include #include #include using namespace std; mutex swapMutex; unsigned long long globalSwapCount = 0 ; /

help check and correct my program
#include
#include
#include
#include
#include
#include
using namespace std;
mutex swapMutex;
unsigned long long globalSwapCount =0;
// Bubble sort function for each thread
void bubbleSort(vector& array, int start, int end, unsigned long long& threadSwapCount){
for (int i = start; i < end -1; ++i){
for (int j = start; j < end - i -1+ start; ++j){
if (array[j]> array[j +1]){
swap(array[j], array[j +1]);
threadSwapCount++;
}
}
}
lock_guard lock(swapMutex);
globalSwapCount += threadSwapCount;
}
// Merge two sorted sections
void mergeSections(vector& array, int start1, int end1, int start2, int end2){
vector temp(end2- start1);
int i = start1, j = start2, k =0;
while (i < end1 && j < end2){
if (array[i]< array[j]) temp[k++]= array[i++];
else temp[k++]= array[j++];
}
while (i < end1) temp[k++]= array[i++];
while (j < end2) temp[k++]= array[j++];
for (int p =0; p < k; ++p) array[start1+ p]= temp[p];
}
int main(){
// Load numbers from file into array
vector array(1000000);
ifstream inFile("numbers.dat");
for (int i =0; i <1000000 && inFile >> array[i]; i++);
inFile.close();
// Initialize threads and swap count for each thread
vector threads;
unsigned long long threadSwapCounts[16]={0};
for (int i =0; i <16; ++i){
int start = i *62500;
int end =(i +1)*62500;
threads.emplace_back(bubbleSort, ref(array), start, end, ref(threadSwapCounts[i]));
}
// Join all threads
for (auto& th : threads) th.join();
// Merge sorted sections iteratively
int sectionSize =62500;
while (sectionSize <1000000){
for (int i =0; i <1000000; i +=2* sectionSize){
int mid = i + sectionSize;
int end = min(i +2* sectionSize,1000000);
if (mid < end) mergeSections(array, i, mid, mid, end);
}
sectionSize *=2;
}
// Output sorted array and global swap count
ofstream outFile("mysort.out");
for (int i =0; i <1000000; i++){
outFile << array[i]<<"";
}
outFile.close();
cout << "Total swaps: "<< globalSwapCount << endl;
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!