int CNegaScout_TT_HH::NegaScout(int depth, int alpha, int beta) { bool bIsSure = false; int Count,i; int a,b,t; int side; int score; int mtype = (m_nMaxDepth%2 == depth%2) ? (-1) : (1); CPublicToMakeMove ptmm; i = IsGameOver(CurPosition, depth,mtype); if (i != 0) return i; side = (m_nMaxDepth-depth)%2; score = LookUpHashTable(alpha, beta, depth, side); if (score != 6666666) { G_nCountTTHH++; return score; } if (depth <= 0) //叶子节点取估值 { int Now1 = GetTickCount(); score = m_pEval->Eveluate(CurPosition,mtype,(m_nMaxDepth-depth)%2); ETime += GetTickCount() - Now1; EnterHashTable(exact, score, depth, side ); return score; } int Now2 = GetTickCount(); Count = m_pMG->CreatePossibleMove(CurPosition, depth, mtype); GTime += GetTickCount() - Now2; if(1 == Count && depth == m_nMaxDepth) { m_cmBestMove = m_pMG->m_nMoveList[depth][0]; return 0; } for (i=0;i<Count;i++) { m_pMG->m_nMoveList[depth][i].Score = GetHistoryScore(&m_pMG->m_nMoveList[depth][i]); } MergeSort(m_pMG->m_nMoveList[depth], Count, 0); int bestmove=-1; a = alpha; b = beta; int eval_is_exact = 0; for ( i = 0; i < Count; i++ ) { Hash_MakeMove(&m_pMG->m_nMoveList[depth][i], CurPosition); MakeMove(&m_pMG->m_nMoveList[depth][i],ptmm); t = -NegaScout(depth-1 , -b, -a); if (t > a && t < beta && i > 0) { a = -NegaScout (depth-1, -beta, -t); /* re-search */ eval_is_exact = 1; if(depth == m_nMaxDepth) { bIsSure = true; Hash_UnMakeMove(&m_pMG->m_nMoveList[depth][i],CurPosition); UnMakeMove(&m_pMG->m_nMoveList[depth][i],ptmm); m_cmBestMove = m_pMG->m_nMoveList[depth][i]; } bestmove = i; } if(bIsSure == false) { Hash_UnMakeMove(&m_pMG->m_nMoveList[depth][i],CurPosition); UnMakeMove(&m_pMG->m_nMoveList[depth][i],ptmm); } else { bIsSure = false; } if (a < t) { eval_is_exact = 1; a=t; if(depth == m_nMaxDepth) m_cmBestMove = m_pMG->m_nMoveList[depth][i]; } if ( a >= beta ) { EnterHashTable(lower_bound, a, depth,side); EnterHistoryScore(&m_pMG->m_nMoveList[depth][i], depth); return a; } b = a + 1; /* set new null window */ } if (bestmove != -1) EnterHistoryScore(&m_pMG->m_nMoveList[depth][bestmove], depth); if (eval_is_exact) EnterHashTable(exact, a, depth,side); else EnterHashTable(upper_bound, a, depth,side); return a; }
int main(int argc, char *argv[]) { int data[] = { 10, 7, 56, 8, 11, 34, 23, 5 }; MergeSort(data, 8); PrintArray(data, 8); }
int main(int argc, char *argv[]) { char inputFile[100], outputFile[100], order[5]; char MemoryAllowed[10]; FILE *metaData; char testColumn[20], temp[200], testColumnSize[20]; int flag, recordSize=0, sublists=0, numberOfRecords = 0; if(argc < 5) { printf("Argument List incomplete!\n"); return 0; } strcpy(inputFile, argv[1]); strcpy(outputFile, argv[2]); strcpy(MemoryAllowed, argv[3]); strcpy(order, argv[4]); int numberOfColumnsSort = argc - 5, i = 0, j, k; char columns[numberOfColumnsSort][5]; int tempCol = numberOfColumnsSort; while(tempCol--) { strcpy(columns[i], argv[5+i]); i++; } int columnNumber[numberOfColumnsSort], len; for (j = 0; j < numberOfColumnsSort; ++j) { len = strlen(columns[j]); columnNumber[j] = 0; for (i = 1; i < len; ++i) { columnNumber[j] += (columns[j][i] - '0') * pow(10, len - 1 - i); } } metaData = fopen("metadata.txt", "r"); if(metaData == NULL) { printf("error in opening file : metadata.txt\n"); return -1; } while(fscanf(metaData, "%s", temp) > 0){ i++; } fclose(metaData); metaData = fopen("metadata.txt", "r"); data *DATA[i]; k = 0; while(fscanf(metaData, "%s", temp) > 0) { i=0; int len = strlen(temp); flag = 0; while(len--) { if(temp[i] == ','){ i++; j = 0; flag = 1; continue; } if(!flag) { testColumn[i] = temp[i]; } else { testColumnSize[j] = temp[i]; j++; } i++; } testColumnSize[j] = '\0'; data *tempNode = NULL; tempNode = (data *)malloc(sizeof(data)); strcpy(tempNode->columnName, testColumn); strcpy(tempNode->size, testColumnSize); tempNode->head = NULL; DATA[k] = tempNode; k++; } fclose(metaData); int maxMemoryAllowed = 0; for (i = 0; i < k; ++i) { len = strlen(DATA[i]->size); for (j = 0; j < len; ++j) { recordSize = recordSize + (DATA[i]->size[j] - '0')*pow(10,len-1-j); } } len = strlen(MemoryAllowed); for (i = 0; i < len; i++) maxMemoryAllowed += (MemoryAllowed[i] - '0')*pow(10, len-1-i); int MaxMem = (int)((0.02)*maxMemoryAllowed*1024*1024)/(recordSize); FILE *input; input = fopen(inputFile, "r"); if(input == NULL) { printf("error in opening file : input.txt\n"); return -1; } FILE *tempFile; tempFile = fopen("temp.txt", "a"); i = 0; j = 0; node *firstNode; node *lastNode[k]; while(1) { if(i==k) { i=0; j++; } int length = 0; int returnValue; char x[200]; if(i == 0) { char c = fgetc(input); length = 0; while(c == '\r' || c == '\n') c = fgetc(input); if(c == EOF) break; while (length != 10) { temp[length++] = c; c = fgetc(input); } temp[length] = '\0'; } else { returnValue = fscanf(input, "%s", temp); if(returnValue < 0) break; } length = strlen(temp); int size = atoi(DATA[i]->size); while(length != size) { char c = fgetc(input); temp[length++] = c; } temp[length] = '\0'; if(j >= MaxMem){ numberOfRecords += j; //printf("**%d**\n", j); sublists++; int l,m; MergeSort(&(DATA[0]->head), columnNumber, order, numberOfColumnsSort); node *Temp; Temp = DATA[0]->head; while(Temp){ for (l = 0; l < k; ++l) { node *Temp2; Temp2 = Temp; for (m = 0; m < l; m++) Temp2 = Temp2->row; if (l != k-1) fprintf(tempFile, "%s ", Temp2->value); else fprintf(tempFile, "%s\n", Temp2->value); } Temp=Temp->column; } j = 0; for (l = 0; l < k; ++l) { node *temp2, *temp1; temp1 = DATA[l]->head->column; while (temp1 != NULL){ temp2 = temp1; temp1 = temp1->column; free(temp2); } DATA[l]->head = NULL; } } node *tempData, *tempData2; node *tempNode; if (DATA[i]->head != NULL) tempData = DATA[i]->head; else tempData = NULL; if (tempData == NULL) { tempNode = (node *)malloc(sizeof(node)); strcpy(tempNode->value, temp); tempNode->column = NULL; tempNode->row = NULL; tempData = tempNode; DATA[i]->head = tempData; if(i!=0) { DATA[i]->head->first = firstNode; DATA[i - 1]->head->row = DATA[i]->head; } else { DATA[i]->head->first = DATA[i]->head; firstNode = DATA[i]->head; } lastNode[i] = DATA[i]->head; } else { tempNode = (node *) malloc(sizeof(node)); strcpy(tempNode->value, temp); tempNode->column = NULL; tempNode->row = NULL; lastNode[i]->column = tempNode; lastNode[i] = tempNode; if(i!=0){ lastNode[i-1]->row = tempNode; } } i++; } fclose(input); numberOfRecords += j; MergeSort(&(DATA[0]->head), columnNumber, order, numberOfColumnsSort); node *Temp; Temp = DATA[0]->head; while(Temp){ for (i = 0; i < k; ++i) { node *Temp2; Temp2 = Temp; for (j = 0; j < i; j++) Temp2 = Temp2->row; if (i != k-1) fprintf(tempFile, "%s ", Temp2->value); else fprintf(tempFile, "%s\n", Temp2->value); } Temp=Temp->column; } for (i = 0; i < k; ++i) { node *temp2, *temp1; temp1 = DATA[i]->head->column; while (temp1 != NULL){ temp2 = temp1; temp1 = temp1->column; free(temp2); } DATA[i]->head = NULL; } sublists++; //printf("Sublists: %d\n", sublists); fclose(tempFile); printf("PHASE-1 OVER\n"); FILE *tempPointer[sublists]; int maxRecords = MaxMem, bytePosition; for (i = 0; i < sublists; ++i) { strcpy(temp, ""); tempPointer[i] = fopen("temp.txt", "r"); bytePosition = (recordSize+(2*(k-1))+1)*maxRecords*i; fseek(tempPointer[i], bytePosition, SEEK_SET); } int checkSublists[sublists], verifySublists[sublists]; for (i = 0; i < sublists; ++i) { checkSublists[i] = 0; if (i != sublists-1) verifySublists[i] = MaxMem; else { verifySublists[i] = numberOfRecords - (sublists-1) * MaxMem; if (verifySublists[i] == 0) { verifySublists[i] = MaxMem; } } } int firstIteration = 0, whichSublist = -1, minPosition = -1; FILE *output; output = fopen(outputFile, "a+"); while(1) { node *Temp, *minTemp; if(firstIteration == 0) { for (j = 0; j < sublists; ++j) { i = 0; while(1) { if (i == k) { i = 0; break; } int length = 0; int returnValue; char x[200]; if(i == 0) { char c = fgetc(tempPointer[j]); length = 0; while(c == '\r' || c == '\n') c = fgetc(tempPointer[j]); int size = atoi(DATA[0]->size); while (length != size) { temp[length++] = c; c = fgetc(tempPointer[j]); } temp[length] = '\0'; } else { returnValue = fscanf(tempPointer[j], "%s", temp); if(returnValue < 0) break; } length = strlen(temp); int size = atoi(DATA[i]->size); while (length != size) { char c = fgetc(tempPointer[j]); temp[length++] = c; } temp[length] = '\0'; node *tempData, *tempData2; node *tempNode; if (DATA[i]->head != NULL) tempData = DATA[i]->head; else tempData = NULL; if (tempData == NULL) { tempNode = (node *)malloc(sizeof(node)); strcpy(tempNode->value, temp); tempNode->column = NULL; tempNode->row = NULL; tempData = tempNode; DATA[i]->head = tempData; if(i!=0) { DATA[i]->head->first = firstNode; DATA[i - 1]->head->row = DATA[i]->head; } else { DATA[i]->head->first = DATA[i]->head; firstNode = DATA[i]->head; } lastNode[i] = DATA[i]->head; } else { tempNode = (node *) malloc(sizeof(node)); strcpy(tempNode->value, temp); tempNode->column = NULL; tempNode->row = NULL; lastNode[i]->column = tempNode; lastNode[i] = tempNode; if(i!=0){ lastNode[i-1]->row = tempNode; } } i++; } } firstIteration = 1; } else if(minPosition >= 0 && ((minPosition == 0 && checkSublists[minPosition] != MaxMem) || (minPosition != 0 && checkSublists[minPosition] != (verifySublists[minPosition])))){ firstIteration = 2; bytePosition = (recordSize+(2*(k-1))+1)*maxRecords*minPosition + (recordSize+(2*(k-1))+1)*checkSublists[minPosition]; fseek(tempPointer[minPosition], bytePosition, SEEK_SET); i = 0; while(1) { if (i == k) { i = 0; break; } int length = 0; int returnValue; char x[200]; if(i == 0) { char c = fgetc(tempPointer[minPosition]); length = 0; while(c == '\r' || c == '\n') c = fgetc(tempPointer[minPosition]); int size = atoi(DATA[0]->size); while (length != size) { temp[length++] = c; c = fgetc(tempPointer[minPosition]); } temp[length] = '\0'; } else { returnValue = fscanf(tempPointer[minPosition], "%s", temp); if(returnValue < 0) break; } length = strlen(temp); int size = atoi(DATA[i]->size); while (length != size) { char c = fgetc(tempPointer[minPosition]); temp[length++] = c; } temp[length] = '\0'; int mPos = i; node *tempNode = minTemp; /*tempNode = DATA[i]->head; while(mPos--) { tempNode = tempNode->column; }*/ while(mPos--) tempNode = tempNode->row; strcpy(tempNode->value, temp); i++; } } Temp = DATA[0]->head; whichSublist = -1; minPosition = -1; int size = atoi(DATA[columnNumber[0]]->size); char tempString[size]; strcpy(tempString, "-1"); while(Temp) { whichSublist++; if(whichSublist == 0) { node *temp1; temp1 = Temp; int cNumber = columnNumber[0]; while(cNumber--){ temp1 = temp1->row; } if (strlen(temp1->value) == size) { strcpy(tempString, temp1->value); minPosition = whichSublist; } minTemp = Temp; } else { node *temp1, *temp2; temp1 = Temp; temp2 = minTemp; int cNumber = columnNumber[0]; while(cNumber--){ temp1 = temp1->row; temp2 = temp2->row; } if(strlen(temp1->value) == size && strcmp(temp2->value, "-1")) { if((strcmp(temp2->value, temp1->value) > 0 && order[0] == 'a') || (strcmp(temp2->value, temp1->value) < 0 && order[0] == 'd')) { minPosition = whichSublist; strcpy(tempString, temp1->value); minTemp = Temp; } else if (strcmp(temp2->value, temp1->value) == 0) { for (i = 1; i < numberOfColumnsSort; ++i) { temp1 = Temp; temp2 = minTemp; cNumber = columnNumber[i]; while (cNumber--) { temp1 = temp1->row; temp2 = temp2->row; } if ((strcmp(temp2->value, temp1->value) > 0 && order[0] == 'a') || (strcmp(temp2->value, temp1->value) < 0 && order[0] == 'd')) { minPosition = whichSublist; minTemp = Temp; break; } } } } else if(strlen(temp1->value) == size && (strcmp(temp2->value, "-1") == 0)) { minPosition = whichSublist; strcpy(tempString, temp1->value); minTemp = Temp; } } Temp = Temp->column; } if (minPosition == -1) break; checkSublists[minPosition]++; int m; for (j = 0; j < k; ++j) { node *Temp2; Temp2 = minTemp; for (m = 0; m < j; m++) Temp2 = Temp2->row; if (j != k-1) { fprintf(output, "%s ", Temp2->value); strcpy(Temp2->value, "-1"); } else { fprintf(output, "%s\r\n", Temp2->value); strcpy(Temp2->value, "-1"); } } } /*for (i = 0; i < sublists; ++i) { printf("Sublist: %d Count: %d\n", i, checkSublists[i]); }*/ return 0; }
void MergeSort(std::vector<int> &A) { if (A.empty()) return; std::vector<int> B(A); MergeSort(A, B, 0, A.size() - 1, 0); }
int main(int argc, char * argv[]) { int numOfLists, sizeOfLists, i, j, bufferItem; double bubBest1, bubWorst1, bubAvg1, bubBest2, bubWorst2, bubAvg2, bubBest3, bubWorst3, bubAvg3, sum1, sum2, sum3; List Lists[1000]; List bufferList; clock_t start1,end1, start2, end2, start3, end3; srand(time(NULL)); if ((argc < 3) || (argc > 3)) { /*Checks preconditions for program*/ printf("**Invalid number of arguments to run program**\n\n**Program will terminate now\n"); return 1; } numOfLists = atoi(argv[1]); sizeOfLists = atoi(argv[2]); /*only lists of size 1000 and up to 1000 lists are supported*/ if ((numOfLists>1000) || (numOfLists<=2) || (sizeOfLists>1000) || (sizeOfLists<=2)) { printf("**Invalid integer entered**\nOnly integers between 3 and 1000 are allowed\nProgram will terminate now\n"); return 1; } Initialize(&bufferList); for (i=0; i<sizeOfLists; i++) { /*Create two mandatory Lists*/ Insert(i+1, i, &Lists[0]); Insert(sizeOfLists-i, i, &Lists[1]); } for (i=2; i<numOfLists; i++) { for (j=0; j<sizeOfLists; j++) { bufferItem = (rand() %343+1); /*Create random lists*/ Insert(bufferItem, bufferList.size, &bufferList); } Lists[i] = bufferList; Initialize(&bufferList); } sum1=0; bubAvg1 = 0; start1 = clock(); /*Starts Timer*/ BubbleSort1(Lists[0]); end1 = clock(); bubBest1 = (double)(end1-start1)/CLOCKS_PER_SEC; start2 = clock(); BubbleSort1(Lists[1]); end2 = clock(); bubWorst1 = (double)(end2-start2)/CLOCKS_PER_SEC; for (i=0; i<numOfLists; i++) { start3 = clock(); BubbleSort1(Lists[i]); end3 = clock(); sum1 = ((double)(end3-start3)/CLOCKS_PER_SEC); bubAvg1 = bubAvg1 + sum1; /*Finds the Average*/ } bubAvg1 = bubAvg1/numOfLists; printf("\nBubbleSort1\n%f\n%f\n%f\n", bubBest1, bubAvg1, bubWorst1); sum2=0; bubAvg2 = 0; start1 = clock(); BubbleSort2(Lists[0]); end1 = clock(); bubBest2 = (double)(end1-start1)/CLOCKS_PER_SEC; start2 = clock(); BubbleSort2(Lists[1]); end2 = clock(); bubWorst2 = (double)(end2-start2)/CLOCKS_PER_SEC; for (i=0; i<numOfLists; i++) { start3 = clock(); BubbleSort2(Lists[i]); end3 = clock(); sum2 = ((double)(end3-start3)/CLOCKS_PER_SEC); bubAvg2 = bubAvg2 + sum2; } bubAvg2 = bubAvg2/numOfLists; printf("\nBubbleSort2\n%f\n%f\n%f\n", bubBest2, bubAvg2, bubWorst2); sum3=0; bubAvg3 = 0; start1 = clock(); MergeSort(&Lists[0], 0, Lists[0].size-1); end1 = clock(); bubBest3 = (double)(end1-start1)/CLOCKS_PER_SEC; start2 = clock(); MergeSort(&Lists[1], 0, Lists[1].size-1); end2 = clock(); bubWorst3 = (double)(end2-start2)/CLOCKS_PER_SEC; for (i=0; i<numOfLists; i++) { start3 = clock(); MergeSort(&Lists[i], 0, Lists[i].size-1); end3 = clock(); sum3 = ((double)(end3-start3)/CLOCKS_PER_SEC); bubAvg3 = bubAvg3 + sum3; } bubAvg3 = bubAvg3/numOfLists; printf("\nMergeSort\n%f\n%f\n%f\n", bubBest3, bubAvg3, bubWorst3); return EXIT_SUCCESS; }
globle void SortFunction( void *theEnv, DATA_OBJECT_PTR returnValue) { long argumentCount, i, j, k = 0; DATA_OBJECT *theArguments, *theArguments2; DATA_OBJECT theArg; struct multifield *theMultifield, *tempMultifield; char *functionName; struct expr *functionReference; int argumentSize = 0; struct FunctionDefinition *fptr; #if DEFFUNCTION_CONSTRUCT DEFFUNCTION *dptr; #endif /*==================================*/ /* Set up the default return value. */ /*==================================*/ SetpType(returnValue,SYMBOL); SetpValue(returnValue,EnvFalseSymbol(theEnv)); /*=============================================*/ /* The function expects at least one argument. */ /*=============================================*/ if ((argumentCount = EnvArgCountCheck(theEnv,"sort",AT_LEAST,1)) == -1) { return; } /*=============================================*/ /* Verify that the comparison function exists. */ /*=============================================*/ if (EnvArgTypeCheck(theEnv,"sort",1,SYMBOL,&theArg) == FALSE) { return; } functionName = DOToString(theArg); functionReference = FunctionReferenceExpression(theEnv,functionName); if (functionReference == NULL) { ExpectedTypeError1(theEnv,"sort",1,"function name, deffunction name, or defgeneric name"); return; } /*======================================*/ /* For an external function, verify the */ /* correct number of arguments. */ /*======================================*/ if (functionReference->type == FCALL) { fptr = (struct FunctionDefinition *) functionReference->value; if ((GetMinimumArgs(fptr) > 2) || (GetMaximumArgs(fptr) == 0) || (GetMaximumArgs(fptr) == 1)) { ExpectedTypeError1(theEnv,"sort",1,"function name expecting two arguments"); ReturnExpression(theEnv,functionReference); return; } } /*=======================================*/ /* For a deffunction, verify the correct */ /* number of arguments. */ /*=======================================*/ #if DEFFUNCTION_CONSTRUCT if (functionReference->type == PCALL) { dptr = (DEFFUNCTION *) functionReference->value; if ((dptr->minNumberOfParameters > 2) || (dptr->maxNumberOfParameters == 0) || (dptr->maxNumberOfParameters == 1)) { ExpectedTypeError1(theEnv,"sort",1,"deffunction name expecting two arguments"); ReturnExpression(theEnv,functionReference); return; } } #endif /*=====================================*/ /* If there are no items to be sorted, */ /* then return an empty multifield. */ /*=====================================*/ if (argumentCount == 1) { EnvSetMultifieldErrorValue(theEnv,returnValue); ReturnExpression(theEnv,functionReference); return; } /*=====================================*/ /* Retrieve the arguments to be sorted */ /* and determine how many there are. */ /*=====================================*/ theArguments = (DATA_OBJECT *) genalloc(theEnv,(argumentCount - 1) * sizeof(DATA_OBJECT)); for (i = 2; i <= argumentCount; i++) { EnvRtnUnknown(theEnv,i,&theArguments[i-2]); if (GetType(theArguments[i-2]) == MULTIFIELD) { argumentSize += GetpDOLength(&theArguments[i-2]); } else { argumentSize++; } } if (argumentSize == 0) { genfree(theEnv,theArguments,(argumentCount - 1) * sizeof(DATA_OBJECT)); /* Bug Fix */ EnvSetMultifieldErrorValue(theEnv,returnValue); ReturnExpression(theEnv,functionReference); return; } /*====================================*/ /* Pack all of the items to be sorted */ /* into a data object array. */ /*====================================*/ theArguments2 = (DATA_OBJECT *) genalloc(theEnv,argumentSize * sizeof(DATA_OBJECT)); for (i = 2; i <= argumentCount; i++) { if (GetType(theArguments[i-2]) == MULTIFIELD) { tempMultifield = (struct multifield *) GetValue(theArguments[i-2]); for (j = GetDOBegin(theArguments[i-2]); j <= GetDOEnd(theArguments[i-2]); j++, k++) { SetType(theArguments2[k],GetMFType(tempMultifield,j)); SetValue(theArguments2[k],GetMFValue(tempMultifield,j)); } } else { SetType(theArguments2[k],GetType(theArguments[i-2])); SetValue(theArguments2[k],GetValue(theArguments[i-2])); k++; } } genfree(theEnv,theArguments,(argumentCount - 1) * sizeof(DATA_OBJECT)); functionReference->nextArg = SortFunctionData(theEnv)->SortComparisonFunction; SortFunctionData(theEnv)->SortComparisonFunction = functionReference; for (i = 0; i < argumentSize; i++) { ValueInstall(theEnv,&theArguments2[i]); } MergeSort(theEnv,(unsigned long) argumentSize,theArguments2,DefaultCompareSwapFunction); for (i = 0; i < argumentSize; i++) { ValueDeinstall(theEnv,&theArguments2[i]); } SortFunctionData(theEnv)->SortComparisonFunction = SortFunctionData(theEnv)->SortComparisonFunction->nextArg; functionReference->nextArg = NULL; ReturnExpression(theEnv,functionReference); theMultifield = (struct multifield *) EnvCreateMultifield(theEnv,(unsigned long) argumentSize); for (i = 0; i < argumentSize; i++) { SetMFType(theMultifield,i+1,GetType(theArguments2[i])); SetMFValue(theMultifield,i+1,GetValue(theArguments2[i])); } genfree(theEnv,theArguments2,argumentSize * sizeof(DATA_OBJECT)); SetpType(returnValue,MULTIFIELD); SetpDOBegin(returnValue,1); SetpDOEnd(returnValue,argumentSize); SetpValue(returnValue,(void *) theMultifield); }
int CNegaScout::NegaScout(int depth, int alpha, int beta) { int Count,i; BYTE type; int a,b,t; int side; int score; i = IsGameOver(CurPosition, depth); if (i != 0) return i; side = (m_nMaxDepth-depth)%2; score = LookUpHashTable(alpha, beta, depth, side); if (score != 66666) return score; if (depth <= 0) //叶子节点取估值 { score = m_pEval->Eveluate(CurPosition, side ); EnterHashTable(exact, score, depth, side ); return score; } Count = m_pMG->CreatePossibleMove(CurPosition, depth, side); for (i=0;i<Count;i++) { m_pMG->m_MoveList[depth][i].Score = GetHistoryScore(&m_pMG->m_MoveList[depth][i]); } MergeSort(m_pMG->m_MoveList[depth], Count, 0); int bestmove=0; a = alpha; b = beta; int eval_is_exact = 0; for ( i = 0; i < Count; i++ ) { Hash_MakeMove(&m_pMG->m_MoveList[depth][i], CurPosition); type = MakeMove(&m_pMG->m_MoveList[depth][i]); t = -NegaScout(depth-1 , -b, -a ); if (t > a && t < beta && i > 0) { a = -NegaScout (depth-1, -beta, -t ); /* re-search */ eval_is_exact = 1; if(depth == m_nMaxDepth) m_cmBestMove = m_pMG->m_MoveList[depth][i]; bestmove = i; } Hash_UnMakeMove(&m_pMG->m_MoveList[depth][i],type, CurPosition); UnMakeMove(&m_pMG->m_MoveList[depth][i],type); if (a < t) { eval_is_exact = 1; a=t; if(depth == m_nMaxDepth) m_cmBestMove = m_pMG->m_MoveList[depth][i]; } if ( a >= beta ) { EnterHashTable(lower_bound, a, depth,side); EnterHistoryScore(&m_pMG->m_MoveList[depth][i], depth); return a; } b = a + 1; /* set new null window */ } EnterHistoryScore(&m_pMG->m_MoveList[depth][bestmove], depth); if (eval_is_exact) EnterHashTable(exact, a, depth,side); else EnterHashTable(upper_bound, a, depth,side); return a; }
auto CountInversionsMergeSort(ArrayType values) { return MergeSort(values.begin(), values.size()); }
void Merge(struct NODE *nodename, int *arrname[]) { system("cls"); MergeSort(arrname, NULL, NULL, NULL); getch(); }
Span *MergeSort(Span *first,int count) { Span *second; if(count==1) //shouldn't happen unless the spanbuffer contains a single span { first->next=NULL; return first; } int n1=count/2; int n2=count-n1; second=first; int t=n1; while((t--)>0) second=second->next; if(n1>1) first=MergeSort(first,n1); else first->next=NULL; if(n2>1) second=MergeSort(second,n2); else second->next=NULL; //merge Span *result_start=NULL; Span *result_end=NULL; //first step done manually switch(SpanCompare(first,second)) { case -1: result_start=first; result_end=first; first=first->next; break; case 0: result_start=first; result_end=second; first=first->next; second=second->next; result_start->next=result_end; break; case 1: result_start=second; result_end=second; second=second->next; break; } while((first!=NULL)&&(second!=NULL)) { switch(SpanCompare(first,second)) { case -1: result_end->next=first; result_end=first; first=first->next; break; case 0: result_end->next=first; result_end=first; first=first->next; result_end->next=second; result_end=second; second=second->next; break; case 1: result_end->next=second; result_end=second; second=second->next; break; } } while((first!=NULL)) { result_end->next=first; result_end=first; first=first->next; } while((second!=NULL)) { result_end->next=second; result_end=second; second=second->next; } result_end->next=NULL; return result_start; }
void MergeSort(WSortView& a) { return MergeSort(a, 0, a.size()); }
/** @brief Main function to get input file name, read file and call mergesort * and print the sorted numbers. * @param number of command line arguments. * @param The address to the inputed file name. * @return 0. */ int main(int argc, char *argv[]) { //Get the input file name. int length=10; printf("\n"); printf("Sorting file : %s\n", argv[1]); int index=0; //Open the input file. FILE *fp = fopen(argv[1], "r"); if (!fp) { perror("encountered fopen error"); exit(10); } //Allocate memory to store numbers in file. int *numbers = (int *) malloc(sizeof(int)*length); //Read numbers from the input file while (fscanf(fp, "%d", &(numbers[index]))==1){ if (index==(length-1)){ length=length*2; numbers = (int *) realloc(numbers,sizeof(int)*length); } index+=1; } // Print the number of elements read. printf("%d elements read\n",index); printf("\n"); //Print the orginal numbers in the input file and put them in a shared memory. printf("Input Numbers:\n"); int size=index*sizeof(int); int shmid; int *shmptr; if ((shmid=shmget(IPC_PRIVATE, size , SHM_MODE))<0){ perror("shmget error"); exit(1); } if ((shmptr=shmat(shmid,0,0))==(void *)-1){ perror("shmat error"); exit(1); } int i; for (i=0;i<index;i++){ shmptr[i]=numbers[i]; printf("%d ",shmptr[i]); } free(numbers); //Call mergesort function and print sorted numbers. printf("\n"); printf("\n"); printf("Sorted Numbers:\n"); if (fclose(fp)) { perror("encountered fclose error"); exit(10); } MergeSort(shmptr,index); for (i=0;i<index;i++){ printf("%d ",shmptr[i]); } printf("\n"); printf("\n"); if (shmctl(shmid, IPC_RMID,0)<0){ perror("shmctl error"); exit(10); } return 0; }
int CNegaScout_TT_HH::NegaScout(int iDepth, int iAlpha, int iBeta) { int iCount,iGameOver; BYTE byChess; int a,b,t; int iSide; int iScore; int i; iGameOver=IsGameOver(byCurChessBoard, iDepth); if(iGameOver!=0) return iGameOver; iSide=(m_iMaxDepth-iDepth)%2;//计算当前节点的类型,极大0/极小1 iScore=LookUpHashTable(iAlpha,iBeta,iDepth,iSide); if(iScore!=66666) return iScore; if(iDepth<=0)//叶子节点取估值 { iScore=m_pEval->Eveluate(byCurChessBoard,iSide); EnterHashTable(Exact,iScore,iDepth,iSide);//将估值存入置换表 return iScore; } iCount=m_pMG->CreatePossibleMove(byCurChessBoard,iDepth,iSide,m_nUserChessColor); if(iDepth==m_iMaxDepth) { //在根节点设定进度条 m_pThinkProgress->SetRange(0,iCount); m_pThinkProgress->SetStep(1); } for(i=0;i<iCount;i++) m_pMG->m_MoveList[iDepth][i].iScore=GetHistoryScore(&m_pMG->m_MoveList[iDepth][i]); MergeSort(m_pMG->m_MoveList[iDepth],iCount,0); int bestmove=-1; a=iAlpha; b=iBeta; int eval_is_exact=0; for(i=0;i<iCount;i++) { if(iDepth==m_iMaxDepth) m_pThinkProgress->StepIt();//走进度条 Hash_MakeMove(&m_pMG->m_MoveList[iDepth][i],byCurChessBoard); byChess=MakeMove(&m_pMG->m_MoveList[iDepth][i]); t=-NegaScout(iDepth-1,-b,-a); if(t>a && t<iBeta && i>0) { //对于第一个后的节点,如果上面的搜索failhigh a=-NegaScout(iDepth-1,-iBeta,-t);//递归搜索子节点 eval_is_exact=1;//设数据类型为精确值 if(iDepth==m_iMaxDepth) m_cmBestMove=m_pMG->m_MoveList[iDepth][i]; bestmove=i; } Hash_UnMakeMove(&m_pMG->m_MoveList[iDepth][i],byChess,byCurChessBoard); UnMakeMove(&m_pMG->m_MoveList[iDepth][i],byChess); if(a<t) { eval_is_exact=1; a=t; if(iDepth==m_iMaxDepth) m_cmBestMove=m_pMG->m_MoveList[iDepth][i]; } if(a>=iBeta) { EnterHashTable(LowerBound,a,iDepth,iSide); EnterHistoryScore(&m_pMG->m_MoveList[iDepth][i],iDepth); return a; } b=a+1;//set new null window } if(bestmove!=-1) EnterHistoryScore(&m_pMG->m_MoveList[iDepth][bestmove],iDepth); if(eval_is_exact) EnterHashTable(Exact,a,iDepth,iSide); else EnterHashTable(UpperBound,a,iDepth,iSide); return a; }
int main(void) { datatype data[N]; datatype temp[N]; int i; srand((unsigned int)time(NULL)); for(i = 0; i < N; i++) { data[i] = rand() % (NUM_LIMITS + 1); } Print(data, N); Copy(data, temp, N); printf("InsertionSort: \n"); InsertionSort(data, N); Print(data, N); Copy(temp, data, N); printf("BinaryInsertionSort:\n"); BinaryInsertionSort(data, N); Print(data, N); Copy(temp, data, N); printf("ShellSort:\n"); ShellSort(data, N); Print(data, N); Copy(temp, data, N); printf("SelectionSort:\n"); SelectionSort(data, N); Print(data, N); Copy(temp, data, N); printf("BubbleSort:\n"); BubbleSort(data, N); Print(data, N); Copy(temp, data, N); printf("QuickSort:\n"); QuickSort(data, 0, N-1); Print(data, N); Copy(temp, data, N); printf("MergeSort:\n"); MergeSort(data, 0, N-1); Print(data, N); Copy(temp, data, N); printf("HeapSort:\n"); HeapSort(data, N); Print(data, N); Copy(temp, data, N); printf("PigeonholeSort:\n"); PigeonholeSort(data, N); Print(data, N); Copy(temp, data, N); printf("BucketSort:\n"); BucketSort(data, N, NUM_LIMITS); Print(data, N); Copy(temp, data, N); printf("CocktailSort:\n"); CocktailSort(data, N); Print(data, N); Copy(temp, data, N); printf("GnomeSort:\n"); GnomeSort(data, N); Print(data, N); Copy(temp, data, N); printf("OddEvenSort:\n"); OddEvenSort(data, N); Print(data, N); Copy(temp, data, N); printf("PatienceSort:\n"); PatienceSort(data, N); Print(data, N); Copy(temp, data, N); printf("BeadSort:\n"); BeadSort(data, N); Print(data, N); Copy(temp, data, N); printf("CombSort:\n"); CombSort(data, N); Print(data, N); Copy(temp, data, N); printf("BogoSort(Do you believe fortune?):\n"); // BogoSort(data, N); // Print(data, N); return 0; }
void MergeJoin (char *infile1, char *infile2, unsigned char field, block_t *buffer, unsigned int nmem_blocks, char *outfile, unsigned int *nres, unsigned int *nios){ //memSize of buffer is -2 cause 2 last blocks is used for, one reading block from big file and two writing to output int memSize = nmem_blocks - 2; //get sizes of files int infile1Size = getSize(infile1); int infile2Size = getSize(infile2); unsigned int noneed1=0, noneed2=0, ios=0; *nres = 0; *nios = 0; FILE *out = fopen(outfile, "ab"); char outfile1[] = "outfile1.bin"; char outfile2[] = "outfile2.bin"; MergeSort(infile1, 1, buffer, nmem_blocks, outfile1, &noneed1, &noneed2, &ios); (*nios) += ios; MergeSort(infile2, 1, buffer, nmem_blocks, outfile2, &noneed1, &noneed2, &ios); (*nios) += ios; //if file1 is bigger switch files cause next we assume that file1 is the small one. if(infile1Size > infile2Size){ char temp0 = outfile1[7]; outfile1[7] = outfile2[7]; outfile2[7] = temp0; int temp = infile1Size; infile1Size = infile2Size; infile2Size = temp; } FILE *input1 = fopen(outfile1, "rb"); FILE *input2 = fopen(outfile2, "rb"); ////printfile(outfile1); ////printfile(outfile2); block_t *bigFileBlock = buffer + memSize; block_t *outputBlock = buffer + memSize + 1; (*outputBlock).blockid = 0; //offset that changes every time we need new block from big file to check int bigFileBlockOffset=0; //counts the records of buffer that has same value of a record of bigFileBlock int countSameBufferEntries=0; //number of blocks in big file. Useful to end the main loop. int blocks = infile2Size - 1; //printf("%d", blocks); //this will represent the id of the first block of the buffer int firstBlockId = 0; int lastBlockId = memSize-1; //at first we read first blocks of small and big file so we have something to compare in first loop (*nios) += readBuffer(buffer, input1, 0, memSize); (*nios) += readBlock(bigFileBlock, input2, 0); recordPos bufferRecPos = getRecordPos(0); record_t tempBufferRec; int tempBufferBlock=0; record_t bigFileBlockRec; while(blocks>0){ /* General: if(bufferRecPos.block%memSize==firstBlockId%memSize) this condition checks if we have reached i circle in the buffer. firstBlockId%memSize defines the first block of the buffer and makes it easy to replace it with another block if necessary with: buffer + firstBlockId%memSize */ for(int blockEntrie=0; blockEntrie<MAX_RECORDS_PER_BLOCK; blockEntrie++){ bigFileBlockRec = (*bigFileBlock).entries[blockEntrie]; if(compareRecords(tempBufferRec, bigFileBlockRec, field)==0){ //Here we have to go back to the block and record of tempBufferRec. for(int i=0; i<countSameBufferEntries; i++){ decr(bufferRecPos); ////printf("%d\n", bufferRecPos.block); } int i=0;//keeps i for load2 int load, load2; if(countSameBufferEntries/memSize > memSize){ load = memSize; load2=0; }else{ load = countSameBufferEntries/memSize; load2 = countSameBufferEntries%memSize; } for( ;i<load; i++){ (*nios) += readBlock(buffer + (tempBufferBlock + i) % memSize, input1, tempBufferBlock + i); } if(load2!=0){//we have to read one more block. (*nios) += readBlock(buffer + (tempBufferBlock + i) % memSize, input1, tempBufferBlock + i); } //return to firstBlockID and lastBlockID their previous values firstBlockId = tempBufferBlock ; lastBlockId = firstBlockId + memSize - 1; } while(compareRecords(getRecord(buffer, bufferRecPos), bigFileBlockRec, field) < 0){ //Here we have to pass the records in the small file that are smaller than the bigFileRec incr(bufferRecPos); if (bufferRecPos.record == 0) { if(bufferRecPos.block%memSize==firstBlockId%memSize){ if (lastBlockId < infile1Size - 1) { (*nios) += readBlock(buffer + firstBlockId%memSize, input1, lastBlockId + 1); firstBlockId += 1; lastBlockId += 1; }else{ blocks=0;//No point to continue merging as all next records are greater than the last of buffer. break; } } } } if(compareRecords(getRecord(buffer, bufferRecPos), bigFileBlockRec, field) > 0){ continue;//... } tempBufferRec = getRecord(buffer, bufferRecPos); tempBufferBlock = bufferRecPos.block; countSameBufferEntries=0; while(compareRecords(getRecord(buffer, bufferRecPos), bigFileBlockRec, field)==0){ //Here we add in output the merges. (*outputBlock).entries[(*outputBlock).nreserved++] = bigFileBlockRec; (*outputBlock).entries[(*outputBlock).nreserved++] = getRecord(buffer, bufferRecPos); (*nres)++; if ((*outputBlock).nreserved == MAX_RECORDS_PER_BLOCK) { (*nios) += writeBlock(out, outputBlock); emptyBlock(outputBlock); (*outputBlock).blockid += 1; } countSameBufferEntries++; incr(bufferRecPos); if(bufferRecPos.record==0){ if(bufferRecPos.block%memSize==firstBlockId%memSize){ if (lastBlockId < infile1Size - 1) { (*nios) += readBlock(buffer + firstBlockId%memSize, input1, lastBlockId + 1); firstBlockId++; lastBlockId++; }else {//take always the same value because it is the last value to compare with last big file's blocks if (bufferRecPos.block == 0) { bufferRecPos.block = memSize - 1; } else { bufferRecPos.block -= 1; } bufferRecPos.record = MAX_RECORDS_PER_BLOCK - 1; break; } } } ////printf("fsdfds"); } } //records in bigFileBlock are over and we read the next one. bigFileBlockOffset++; blocks--; (*nios) += readBlock(bigFileBlock, input2, bigFileBlockOffset); } }
int main(int argc, char *argv[]) { struct timeval startTime, endTime; gettimeofday(&startTime, NULL); if(argc != 4) { printf("Please enter valid files: inputFile outputCountFile outputRuntimeFile\n"); return 0; } FILE *inputFile; char wordOne[1000]; Word *curr, *head; Word *curr2; head = curr = NULL; curr2 = head; inputFile = fopen(argv[1], "r"); //while(fgets(wordOne,sizeof(wordOne),inputFile)) while(fscanf(inputFile,"%s",wordOne)==1) { Word *node = malloc(sizeof(Word)); char *temp = strdup(wordOne); convertToNormal(temp); node->word = (strdup(temp)); node -> next=NULL; if(head ==NULL) { curr = head = node; } else { curr = curr->next=node; } } fclose(inputFile); MergeSort(&head); FILE *countFile; countFile = fopen(argv[2],"w"); for(curr = head; curr; curr = curr->next) curr->count = curr->count++; for(curr = head; curr; curr = curr->next) { while((curr->next != NULL) && strcmp(curr->word,curr->next->word) == 0) { if((curr->next != NULL) && strcmp(curr->word,curr->next->word) == 0) { curr->count = curr->count++; curr->next = curr->next->next; } } } for(curr = head; curr; curr = curr->next) { fprintf(countFile, "%s, %d\n", curr->word, curr->count); } fclose(countFile); freeMem(head); gettimeofday(&endTime, NULL); unsigned int runtime = endTime.tv_usec - startTime.tv_usec; FILE *fRuntime; fRuntime=fopen(argv[3], "w"); fprintf(fRuntime,"The runtime is %d\n" , runtime); fclose(fRuntime); return 0; }
void MergeSortTextComp(char *srcFile, char *destFile, sint (*funcComp)(char *, char *), uint partSize) { MergeSort(srcFile, destFile, 1, (uint (*)(FILE *))readLine, (void (*)(FILE *, uint))writeLine_x, (sint (*)(uint, uint))funcComp, partSize); }
void mergesort(int *array, const unsigned int size) { MergeSort(array, 0, size - 1); raiseEvent(EVENT_TYPE_END, 0); }
int main(int argc, char* argv[]) { int seed = 40; int n = 10; int max = 100; int *a = nullptr; // Insertion sort a = CreatA(a, n, seed, max); printArray(a, n, "Original"); InsertionSort(a, n); //printArray(a, n, "InsertSort"); VerifySorted(a, n); // Selection sort a = CreatA(a, n, seed, max); SelectionSort(a, n); //printArray(a, n, "selectSort"); VerifySorted(a, n); a = CreatA(a, n, seed, max); MergeSort(a, n); //printArray(a, n, "MergeSort"); VerifySorted(a, n); a = CreatA(a, n, seed, max); QuickSort(a, n); //printArray(a, n, "QuickSort"); VerifySorted(a, n); a = CreatA(a, n, seed, max); BubbleSort(a, n); printArray(a, n, "BubbleSort"); VerifySorted(a, n); int value = 22; //BinarySearch(a, n, value); //BinarySearchIter(a, n, value); //RunBinarySearchCircular(a, n, value); value = 27; /*BinarySearch(a, n, value); BinarySearchIter(a, n, value); RunBinarySearchCircular(a, n, value); */ a = CreatA(a, n, seed, max); printArray(a, n, "Pre min heap sort"); RunSortMinHeap(a, n); printArray(a, n, "MinHeapSort"); VerifySorted(a, n); a = CreatA(a, n, seed, max); printArray(a, n, "Pre max heap sort"); RunSortMaxHeap(a, n); printArray(a, n, "MaxHeapSort"); VerifySorted(a, n); printf("\nMedian %d\n", Median(a, n)); return 0; }
int main(int argc, char **argv) { #if 1 if(0 == isArbiterExist()) { marbit_send_log(ERROR,"arbiter is not start!\n"); exit(1); } #endif //init sys info if(0 != init_sys_info()) { marbit_send_log(ERROR,"Failed to init_sys_info!\n"); exit(1); } //parse the parameters if(0 != parse_input_parameters(argc, argv)) { destroy_info(); input_error(); exit(1); } //time_t begin_time = time(NULL); // time_t do_process_data_stream_time= time(NULL); // time_t do_process_data_aggregation_time= time(NULL); // time_t do_process_sort_time = time(NULL); // time_t print_baselink_time = time(NULL); //time_t print_sorted_list_time = time(NULL); struct timeval start, getFromArbiter, printLink, dataAggregation, quickSort, printSort, end; gettimeofday( &start, NULL ); #if 1 //data_stream, check need get data stream from arbiter or configure file if(0 == isNeedReadFromDB(DATA_STREAM_FILE_PATH, g_flush_interval)) { //set_timer(); if(0 != do_process_from_arbiter()) { marbit_send_log(ERROR,"Failed to get data stream from arbiter\n"); exit(1); } } gettimeofday( &getFromArbiter, NULL ); #endif if(SORTED_BASE_LINK == g_sorted_list_index) { print_baselink_info(DATA_STREAM_FILE_PATH); gettimeofday( &printLink, NULL ); } else if(SORTED_BASE_APP == g_sorted_list_index || SORTED_BASE_IP == g_sorted_list_index) { //data_aggregation do_process_data_aggregation(); gettimeofday( &dataAggregation, NULL ); #if 1 MergeSort(&merglist); gettimeofday( &quickSort, NULL ); printMergeList(merglist); gettimeofday( &printSort, NULL ); destroyMergelist(merglist); #else struct list_head *head = &sorted_list_arry[SORTED_BASE_AGG].list; //struct list_head *head = &sorted_list_arry[g_sorted_list_index].list; struct list_head *first = head->next; struct list_head *last = head->prev; sorted_node_t *pstHead = list_entry(head, sorted_node_t, list); quick_sort(head, first, last); gettimeofday( &quickSort, NULL ); print_sorted_list(SORTED_BASE_AGG); //print_sorted_list(g_sorted_list_index); gettimeofday( &printSort, NULL ); #endif } destroy_info(); gettimeofday( &end, NULL ); if(logdebug.g_trace_enable_flag > 0) { marbit_send_log(INFO,"=======================================\n"); int timeuse = 0; if(SORTED_BASE_LINK == g_sorted_list_index) { timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec; marbit_send_log(INFO,"all used time = %lu us\n", timeuse); timeuse = 1000000 * ( getFromArbiter.tv_sec - start.tv_sec ) + getFromArbiter.tv_usec - start.tv_usec; marbit_send_log(INFO,"getFromArbiter used time = %lu us\n", timeuse); timeuse = 1000000 * ( printLink.tv_sec - getFromArbiter.tv_sec ) + printLink.tv_usec - getFromArbiter.tv_usec; marbit_send_log(INFO,"printLink used time = %lu us\n", timeuse); timeuse = 1000000 * ( end.tv_sec - printLink.tv_sec ) + end.tv_usec - printLink.tv_usec; marbit_send_log(INFO,"destroy used time = %lu us\n", timeuse); } else { timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec; marbit_send_log(INFO,"all used time = %lu us\n", timeuse); timeuse = 1000000 * ( getFromArbiter.tv_sec - start.tv_sec ) + getFromArbiter.tv_usec - start.tv_usec; marbit_send_log(INFO,"getFromArbiter used time = %lu us\n", timeuse); timeuse = 1000000 * ( dataAggregation.tv_sec - getFromArbiter.tv_sec ) + dataAggregation.tv_usec - getFromArbiter.tv_usec; marbit_send_log(INFO,"dataAggregation used time = %lu us\n", timeuse); timeuse = 1000000 * ( quickSort.tv_sec - dataAggregation.tv_sec ) + quickSort.tv_usec - dataAggregation.tv_usec; marbit_send_log(INFO,"quickSort used time = %lu us\n", timeuse); timeuse = 1000000 * ( printSort.tv_sec - quickSort.tv_sec ) + printSort.tv_usec - quickSort.tv_usec; marbit_send_log(INFO,"printSort used time = %lu us\n", timeuse); timeuse = 1000000 * ( end.tv_sec - printSort.tv_sec ) + end.tv_usec - printSort.tv_usec; marbit_send_log(INFO,"destroy used time = %lu us\n", timeuse); } } return 0; }
struct node * sortLinkedList(struct node *head) { struct node *temp; temp = MergeSort(&head); return temp; }
/** encode string by global fit */ void globalfit_encode(ReconStructure *recStr, ReconStructure *tempRecStr, Vec *refcoord, FragmentSet *fragment_set, Str *fragment_str, int pos, int heapsize) { int i, j, k; /* counter */ int overlap = 3; /* size of overlap */ Vec *fragCoord; /* fragment coordinates */ int heapCount = 0; /* counter for structure in the heap */ int (*fcmp)() = &RecStrCmp; int idx; /** symmetry operators for structural superpositioning */ gsl_matrix *U = 0; /* rotation matrix */ gsl_vector *t = 0; /* translation vector */ gsl_matrix *X = 0; /* structure fragment matrix query */ gsl_matrix *Y = 0; /* structure fragment matrix template */ /* allocate memory for fragment coordinates */ fragCoord = safe_malloc(fragment_set->lFragment * sizeof(Vec)); /* at the beginning of the reconstruction the head of the heap is * filled with the fragments */ if (pos == 0) { /* allocate memory for kabsch matrices */ kabsch_alloc(&U, &t, &X, &Y, fragment_set->lFragment); for(i = 0; i < fragment_set->nFragment; ++ i) { for (j = 0; j < fragment_set->lFragment; j ++) { fragCoord[j].x = fragment_str[i].atom[j].pos.x; fragCoord[j].y = fragment_str[i].atom[j].pos.y; fragCoord[j].z = fragment_str[i].atom[j].pos.z; } recStr[i].rmsd = superimpose_segment(X, Y, U, t, &refcoord[pos], fragCoord, &recStr[i].coord[pos], fragment_set->lFragment); recStr[i].encodedString[pos] = fragment_set->codeOrder[i]; recStr[i].encodedString[pos + 1] = '\0'; } } else { /* allocate memory for kabsch matrices */ kabsch_alloc(&U, &t, &X, &Y, overlap); for(k = 0; k < heapsize; ++ k) { if (strcmp(recStr[k].encodedString, "") != 0) { for(i = 0; i < fragment_set->nFragment; ++ i) { idx = k * fragment_set->nFragment + i; for (j = 0; j < fragment_set->lFragment; j ++) { fragCoord[j].x = fragment_str[i].atom[j].pos.x; fragCoord[j].y = fragment_str[i].atom[j].pos.y; fragCoord[j].z = fragment_str[i].atom[j].pos.z; } tempRecStr[idx].rmsd = extend_segment(X, Y, U, t, recStr[k].coord, fragCoord, tempRecStr[idx].coord, refcoord, pos + overlap, fragment_set->lFragment, overlap); strcpy(tempRecStr[idx].encodedString, recStr[k].encodedString); tempRecStr[idx].encodedString[pos] = fragment_set->codeOrder[i]; tempRecStr[idx].encodedString[pos + 1] = '\0'; heapCount += 1; } } } /* check if tentative structures are more than what the heap can hold */ if (heapCount < heapsize) { /* sort temporary reconstructed structures array by RMSD */ MergeSort(tempRecStr, heapCount, sizeof(ReconStructure), fcmp); /* copy from temporary reconstructed structures array */ for(k = 0; k < heapsize; ++ k) if (strcmp(tempRecStr[k].encodedString, "") != 0) RecStrCpy(&recStr[k], &tempRecStr[k]); } else { /* sort temporary reconstructed structures array by RMSD */ MergeSort(tempRecStr, heapCount, sizeof(ReconStructure), fcmp); /* copy best RMSD structures to reconstructed structures array */ for(k = 0; k < heapsize; ++ k) RecStrCpy(&recStr[k], &tempRecStr[k]); } } /* free memory from kabsch matrices */ kabsch_free(U, t, X, Y); /* free memory from fragment coordinates */ free(fragCoord); }
int main(){ clock_t t1, t2; int i; float diff; srand(time(NULL)); int Array1[Size1]; int Array2[Size2]; int Array3[Size3]; int Array4[Size4]; long long int AVGBaseOp1=0,AVGBaseOp2=0,AVGBaseOp3=0,AVGBaseOp4=0; float AVGTime1=0,AVGTime2=0,AVGTime3=0,AVGTime4=0; long int Comparison; //**************************************************************** //BEST & WORST CASES for(i=0;i<4;i++){ //********************** Comparison=0; CreateAnArray(Array4,Size4,i+1,0); t1=clock(); Comparison=InsertionSort(Array4,Size4); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime1=diff; AVGBaseOp1=Comparison; //********************* Comparison=0; CreateAnArray(Array4,Size4,i+1,0); t1=clock(); MergeSort(Array4,0,Size4-1,Size4,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime2=diff; AVGBaseOp2=Comparison; //********************* Comparison=0; CreateAnArray(Array4,Size4,i+1,0); t1=clock(); QuickSort(Array4,0,Size4-1,1,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime3=diff; AVGBaseOp3=Comparison; //******************** Comparison=0; CreateAnArray(Array4,Size4,i+1,0); t1=clock(); QuickSort(Array4,0,Size4-1,2,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime4=diff; AVGBaseOp4=Comparison; printf("\nBest And WOrst Cases With Array Size 5000\n"); if(i==0)printf("Totaly Random Array\n\n"); if(i==1)printf("Sorted Array\n\n"); if(i==2)printf("Reverse Sorted Array\n\n"); if(i==3)printf("Array With All Elements are Equal\n\n"); printf("\t\tInsertionSort\t\tMergeSort\n\n"); if(i==1 || i==3) printf("AverageBaseOp:\t%ld\t\t\t%ld\n",AVGBaseOp1,AVGBaseOp2); else printf("AverageBaseOp:\t%ld\t\t%ld\n",AVGBaseOp1,AVGBaseOp2); printf("AverageTime:\t%lf\t\t%lf\n",AVGTime1,AVGTime2); printf("\t\tQuickSort1\t\tQuickSort2\n\n"); printf("AverageBaseOp:\t%ld\t\t\t%ld\n",AVGBaseOp3,AVGBaseOp4); printf("AverageTime:\t%lf\t\t%lf\n\n",AVGTime3,AVGTime4); } //**************************************************************** for(i=0;i<30;i++){ //******************************* Comparison=0; if(i<10){ CreateAnArray(Array1,Size1,2,((i+1)*3200)); } else if(i<20){ CreateAnArray(Array1,Size1,3,((i+1)*3200)); } else{ CreateAnArray(Array1,Size1,1,0);} t1=clock(); Comparison=InsertionSort(Array1,Size1); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime1+=diff; AVGBaseOp1+=Comparison; //********************************* Comparison=0; if(i<10){ CreateAnArray(Array1,Size1,2,((i+1)*3200)); } else if(i<20){ CreateAnArray(Array1,Size1,3,((i+1)*3200)); } else{ CreateAnArray(Array1,Size1,1,0);} t1=clock(); MergeSort(Array1,0,Size1-1,Size1,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime2+=diff; AVGBaseOp2+=Comparison; //********************************** Comparison=0; if(i<10){ CreateAnArray(Array1,Size1,2,((i+1)*3200)); } else if(i<20){ CreateAnArray(Array1,Size1,3,((i+1)*3200)); } else{ CreateAnArray(Array1,Size1,1,0);} t1=clock(); QuickSort(Array1,0,Size1-1,1,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime3+=diff; AVGBaseOp3+=Comparison; //********************************** Comparison=0; if(i<10){ CreateAnArray(Array1,Size1,2,((i+1)*3200)); } else if(i<20){ CreateAnArray(Array1,Size1,3,((i+1)*3200)); } else{ CreateAnArray(Array1,Size1,1,0);} t1=clock(); QuickSort(Array1,0,Size1-1,2,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime4+=diff; AVGBaseOp4+=Comparison; } printf("\n\nQuickSort1: Pivot always selected as first element.\nQuickSort2: Pivot always selected as mediand of three elements\n\n\n"); printf("ArraySize: 40000\n"); printf("\t\tInsertionSort\t\tMergeSort\n"); printf("AverageBaseOp:\t%ld\t\t%ld\n",AVGBaseOp1/30,AVGBaseOp2/30); printf("AverageTime:\t%lf\t\t%lf\n\n",AVGTime1/30,AVGTime2/30); printf("\t\tQuickSort1\t\tQuickSort2\n"); printf("AverageBaseOp:\t%ld\t\t\t%ld\n",AVGBaseOp3/30,AVGBaseOp4/30); printf("AverageTime:\t%lf\t\t%lf\n\n\n",AVGTime3/30,AVGTime4/30); AVGTime1=0;AVGTime2=0;AVGTime3=0;AVGTime4=0; AVGBaseOp1=0;AVGBaseOp2=0;AVGBaseOp3=0;AVGBaseOp4=0; for(i=0;i<30;i++){ //********************************* Comparison=0; if(i<10){ CreateAnArray(Array2,Size2,2,((i+1)*2000)); } else if(i<20){ CreateAnArray(Array2,Size2,3,((i+1)*2000)); } else{ CreateAnArray(Array2,Size2,1,0);} t1=clock(); Comparison=InsertionSort(Array2,Size2); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime1+=diff; AVGBaseOp1+=Comparison; //********************************* Comparison=0; if(i<10){ CreateAnArray(Array2,Size2,2,((i+1)*2000)); } else if(i<20){ CreateAnArray(Array2,Size2,3,((i+1)*2000)); } else{ CreateAnArray(Array2,Size2,1,0);} t1=clock(); MergeSort(Array2,0,Size2-1,Size2,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime2+=diff; AVGBaseOp2+=Comparison; //******************************* Comparison=0; if(i<10){ CreateAnArray(Array2,Size2,2,((i+1)*2000)); } else if(i<20){ CreateAnArray(Array2,Size2,3,((i+1)*2000)); } else{ CreateAnArray(Array2,Size2,1,0);} t1=clock(); QuickSort(Array2,0,Size2-1,1,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime3+=diff; AVGBaseOp3+=Comparison; //***************************** Comparison=0; if(i<10){ CreateAnArray(Array2,Size2,2,((i+1)*2000)); } else if(i<20){ CreateAnArray(Array2,Size2,3,((i+1)*2000)); } else{ CreateAnArray(Array2,Size2,1,0);} t1=clock(); QuickSort(Array2,0,Size2-1,2,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime4+=diff; AVGBaseOp4+=Comparison; } printf("ArraySize: 25000\n"); printf("\t\tInsertionSort\t\tMergeSort\n"); printf("AverageBaseOp:\t%ld\t\t%ld\n",AVGBaseOp1/30,AVGBaseOp2/30); printf("AverageTime:\t%lf\t\t%lf\n\n",AVGTime1/30,AVGTime2/30); printf("\t\tQuickSort1\t\tQuickSort2\n"); printf("AverageBaseOp:\t%ld\t\t\t%ld\n",AVGBaseOp3/30,AVGBaseOp4/30); printf("AverageTime:\t%lf\t\t%lf\n\n\n",AVGTime3/30,AVGTime4/30); AVGTime1=0;AVGTime2=0;AVGTime3=0;AVGTime4=0; AVGBaseOp1=0;AVGBaseOp2=0;AVGBaseOp3=0;AVGBaseOp4=0; for(i=0;i<30;i++){ //******************************** Comparison=0; if(i<10){ CreateAnArray(Array3,Size3,2,((i+1)*800)); } else if(i<20){ CreateAnArray(Array3,Size3,3,((i+1)*800)); } else{ CreateAnArray(Array3,Size3,1,0);} t1=clock(); Comparison=InsertionSort(Array3,Size3); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime1+=diff; AVGBaseOp1+=Comparison; //***************************** Comparison=0; if(i<10){ CreateAnArray(Array3,Size3,2,((i+1)*800)); } else if(i<20){ CreateAnArray(Array3,Size3,3,((i+1)*800)); } else{ CreateAnArray(Array3,Size3,1,0);} t1=clock(); MergeSort(Array3,0,Size3-1,Size3,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime2+=diff; AVGBaseOp2+=Comparison; //***************************** Comparison=0; if(i<10){ CreateAnArray(Array3,Size3,2,((i+1)*800)); } else if(i<20){ CreateAnArray(Array3,Size3,3,((i+1)*800)); } else{ CreateAnArray(Array3,Size3,1,0);} t1=clock(); QuickSort(Array3,0,Size3-1,1,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime3+=diff; AVGBaseOp3+=Comparison; //**************************** Comparison=0; if(i<10){ CreateAnArray(Array3,Size3,2,((i+1)*800)); } else if(i<20){ CreateAnArray(Array3,Size3,3,((i+1)*800)); } else{ CreateAnArray(Array3,Size3,1,0);} t1=clock(); QuickSort(Array3,0,Size3-1,2,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime4+=diff; AVGBaseOp4+=Comparison; } printf("ArraySize: 10000\n"); printf("\t\tInsertionSort\t\tMergeSort\n"); printf("AverageBaseOp:\t%ld\t\t%ld\n",AVGBaseOp1/30,AVGBaseOp2/30); printf("AverageTime:\t%lf\t\t%lf\n\n",AVGTime1/30,AVGTime2/30); printf("\t\tQuickSort1\t\tQuickSort2\n"); printf("AverageBaseOp:\t%ld\t\t\t%ld\n",AVGBaseOp3/30,AVGBaseOp4/30); printf("AverageTime:\t%lf\t\t%lf\n\n\n",AVGTime3/30,AVGTime4/30); AVGTime1=0;AVGTime2=0;AVGTime3=0;AVGTime4=0; AVGBaseOp1=0;AVGBaseOp2=0;AVGBaseOp3=0;AVGBaseOp4=0; for(i=0;i<30;i++){ //******************************* Comparison=0; if(i<10){ CreateAnArray(Array4,Size4,2,((i+1)*400)); } else if(i<20){ CreateAnArray(Array4,Size4,3,((i+1)*400)); } else{ CreateAnArray(Array4,Size4,1,0);} t1=clock(); Comparison=InsertionSort(Array4,Size4); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime1+=diff; AVGBaseOp1+=Comparison; //********************************* Comparison=0; if(i<10){ CreateAnArray(Array4,Size4,2,((i+1)*400)); } else if(i<20){ CreateAnArray(Array4,Size4,3,((i+1)*400)); } else{ CreateAnArray(Array4,Size4,1,0);} t1=clock(); MergeSort(Array4,0,Size4-1,Size4,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime2+=diff; AVGBaseOp2+=Comparison; //********************************** Comparison=0; if(i<10){ CreateAnArray(Array4,Size4,2,((i+1)*400)); } else if(i<20){ CreateAnArray(Array4,Size4,3,((i+1)*400)); } else{ CreateAnArray(Array4,Size4,1,0);} t1=clock(); QuickSort(Array4,0,Size4-1,1,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime3+=diff; AVGBaseOp3+=Comparison; //********************************** Comparison=0; if(i<10){ CreateAnArray(Array4,Size4,2,((i+1)*400)); } else if(i<20){ CreateAnArray(Array4,Size4,3,((i+1)*400)); } else{ CreateAnArray(Array4,Size4,1,0);} t1=clock(); QuickSort(Array4,0,Size4-1,2,&Comparison); t2=clock(); diff = (((float)t2 - (float)t1) / 1000000.0F ) * 1000; AVGTime4+=diff; AVGBaseOp4+=Comparison; } printf("ArraySize: 5000\n"); printf("\t\tInsertionSort\t\tMergeSort\n"); printf("AverageBaseOp:\t%lld\t\t%lld\n",AVGBaseOp1/30,AVGBaseOp2/30); printf("AverageTime:\t%lf\t\t%lf\n\n",AVGTime1/30,AVGTime2/30); printf("\t\tQuickSort1\t\tQuickSort2\n"); printf("AverageBaseOp:\t%lld\t\t\t%lld\n",AVGBaseOp3/30,AVGBaseOp4/30); printf("AverageTime:\t%lf\t\t%lf\n\n\n",AVGTime3/30,AVGTime4/30); }