예제 #1
0
 long long reversePairs(vector<int>& A) 
 {
     mergeSort(A);
     return count;
 }
void qtSearchWindow::query(){
	//clean up the data from last search
	resultNameList->clear();
	searchResult.clear();
	PageRankGraph.clear();
	//new search
	QString qstr; 
	webpagePageRankComp pageRankComp;
	if(queryInput->text().isEmpty()){
		return;
	}
	userQuery = queryInput->text().toStdString();
	if(singleOption->isChecked()){
		searchengine.parseRequest(userQuery, wrongFormat, webpagesContainingFirstWord, webpagesContainingSecondWord);
	}
	else if(andOption->isChecked()){
		userQuery = "AND "+userQuery;
		searchengine.parseRequest(userQuery, wrongFormat, webpagesContainingFirstWord, webpagesContainingSecondWord);
	}
	else if(orOption->isChecked()){
		userQuery = "OR "+userQuery;
		searchengine.parseRequest(userQuery, wrongFormat, webpagesContainingFirstWord, webpagesContainingSecondWord);
	}
	////the search process finished here
	//check if the result is wrong format
	if(wrongFormat){
		QMessageBox msgBox;
		msgBox.setWindowTitle("Oops!");
		msgBox.setText("\"Oops! Seems that your query format is invalid!\"");
		msgBox.setStandardButtons(QMessageBox::Yes);
		msgBox.setDefaultButton(QMessageBox::Yes);
		msgBox.exec();
	}
	else{
		myset<WebPage*> extended;
		for(set<WebPage*>::iterator it = webpagesContainingFirstWord.begin();
      		it != webpagesContainingFirstWord.end();
      		++it){

	  		myset<WebPage*> allin = (**it).incoming_links();
	  		myset<WebPage*> allOut = (**it).outgoing_links();
	  		for(set<WebPage*>::iterator itIn = allin.begin();
      		itIn != allin.end();
      		++itIn){
      			if(extended.count(*itIn)==0){ //maybe here check if the link exists
      				extended.insert(*itIn);
      			}
      		}
      		for(set<WebPage*>::iterator itOut = allOut.begin();
      		itOut != allOut.end();
      		++itOut){
	  			if(extended.count(*itOut)==0){ //maybe here check if the link exists
      				extended.insert(*itOut);
      			}
      		}
      	}
      	webpagesContainingFirstWord = webpagesContainingFirstWord.set_union(extended);
      	extended.clear();
		for(set<WebPage*>::iterator it = webpagesContainingFirstWord.begin();
      		it != webpagesContainingFirstWord.end();
      		++it){
			searchResult.push_back(*it);
		}
		//display the result by default, sorted by filenames 
		if(searchResult.size()==0){
			QMessageBox msgBox;
			msgBox.setWindowTitle("Oops!");
			msgBox.setText("\"0 Hits! None of the website contains your words\"");
			msgBox.setStandardButtons(QMessageBox::Yes);
			msgBox.setDefaultButton(QMessageBox::Yes);
			msgBox.exec();
		}
		else{

			//for each webpage in the candidate set, count the valid in/out links and map them
			for(int i=0; i<(int)searchResult.size();i++){
				//initialize this node, map it to the webpage
				int initialization_link = 0;	
				int initialization_link2 = 0;
				double initialization_pagevalue = 1/(double)searchResult.size();
				node newNode;
				newNode.numberOfValidIncomingLinks = initialization_link;
				newNode.numberOfValidOutgoingLinks = initialization_link2;
				newNode.currentPageRankValue = initialization_pagevalue;
				PageRankGraph[searchResult[i]] = newNode;

				//identify the incoming and outgoing degree of this node
				//indentify the set of in/out links within the candidate set(valid)
	  			myset<WebPage*> allin = searchResult[i]->incoming_links();
	  			myset<WebPage*> allOut = searchResult[i]->outgoing_links();
	  			for(set<WebPage*>::iterator itIn = allin.begin();
      			itIn != allin.end();
      			++itIn){
      				if(webpagesContainingFirstWord.count(*itIn)==1){	//maybe here check if the link exists
      					PageRankGraph[searchResult[i]].numberOfValidIncomingLinks += 1;
      					PageRankGraph[searchResult[i]].ValidIncomingLinks.insert(*itIn); 
      				}
      			}
      			for(set<WebPage*>::iterator itOut = allOut.begin();
      			itOut != allOut.end();
      			++itOut){
      				if(webpagesContainingFirstWord.count(*itOut)==1){	//maybe here check if the link exists
      					PageRankGraph[searchResult[i]].numberOfValidOutgoingLinks += 1;
      					PageRankGraph[searchResult[i]].ValidOutgoingLinks.insert(*itOut); 
      				}
      			}

      			//adding self-links
      			if(PageRankGraph[searchResult[i]].ValidIncomingLinks.count(searchResult[i])==0){
      				PageRankGraph[searchResult[i]].numberOfValidIncomingLinks += 1;
      				PageRankGraph[searchResult[i]].ValidIncomingLinks.insert(searchResult[i]);
      			}
      			if(PageRankGraph[searchResult[i]].ValidOutgoingLinks.count(searchResult[i])==0){
      				PageRankGraph[searchResult[i]].numberOfValidOutgoingLinks += 1;
      				PageRankGraph[searchResult[i]].ValidOutgoingLinks.insert(searchResult[i]);
      			}
			}
			//after the initializataion above, start iteration to calculate pagerank for each page
			for(int i=0; i<PageRankSteps; i++){
				for(std::map<WebPage*, node>::iterator itmap = PageRankGraph.begin();
					itmap != PageRankGraph.end();
					++itmap){

					double newPageRankValue = 0;
					//With the remaining probability 1-ε, he follows an outgoing link (chosen uniformly at random) from his current node v. That is, for each directed edge (v,u) (including the self loop), 
					//he next goes to u with probability 1/d+(v).
					for(set<WebPage*>::iterator itIn = itmap->second.ValidIncomingLinks.begin();
	      			itIn != itmap->second.ValidIncomingLinks.end();
	      			++itIn){
						newPageRankValue += (1-Restart_Probability)*(PageRankGraph[*itIn].currentPageRankValue)/(double)(PageRankGraph[*itIn].numberOfValidOutgoingLinks);
					}
					newPageRankValue += Restart_Probability/searchResult.size();
					//dynamically compute new pagevalue of this node, store it in PageRANK of a webpage
					itmap->first->setPageRank(newPageRankValue);
				}
				//now we compute all the new pagerank value after one iteration, update it
				for(std::map<WebPage*, node>::iterator itmap = PageRankGraph.begin();
					itmap != PageRankGraph.end();
					++itmap){
				itmap->second.currentPageRankValue = itmap->first->getPageRank();
				}
			}

			//here we finish calculating page rank for each page after given number of iterations
			//now we sort them by PageRank (default)
			mergeSort(searchResult, pageRankComp);

			for(int i=0; i<(int)searchResult.size();i++){
			qstr = QString::fromStdString(searchResult[i]->filename());
			qstr = qstr + "	IncomingLinks:" + QString::number(searchResult[i]->incoming_links().size());
			qstr = qstr + "	OutgoingLinks:" + QString::number(searchResult[i]->outgoing_links().size());
			qstr = qstr + "	PageRank:" + QString::number(PageRankGraph[searchResult[i]].currentPageRankValue);
			resultNameList->addItem(qstr);
			}	
		}	
	}
	resultNameList->setCurrentRow(0);
	//after fetching, clean up the data to prepare for next search
	queryInput->setText("");
	wrongFormat=false;
    webpagesContainingFirstWord.clear();
    webpagesContainingSecondWord.clear();
}
예제 #3
0
int average(int *array1, int size, int code)
{
	int array2[size];
	int array3[size];
	int array4[size];
	int array5[size];
	int array6[size];
	int array7[size];
	int array8[size];
	int array9[size];
	int array10[size];
	int i;
	double time = 0;
	clock_t start_t, end_t;
	
	//copies array1 to the rest of the arrays
	for(i = 0; i <= size; i++)
	{
		array2[i] = array1[i];
		array3[i] = array1[i];
		array4[i] = array1[i];
		array5[i] = array1[i];
		array6[i] = array1[i];
		array7[i] = array1[i];
		array8[i] = array1[i];
		array9[i] = array1[i];
	}

	switch(code)
	{
		case 1: start_t = clock();
				insertionSort(array1, size);	
				insertionSort(array2, size);	
				insertionSort(array3, size);
				insertionSort(array4, size);	
				insertionSort(array5, size);	
				insertionSort(array6, size);	
				insertionSort(array7, size);	
				insertionSort(array8, size);	
				insertionSort(array9, size);	
				insertionSort(array10, size);	
				end_t = clock();
				time = (double)(end_t - start_t);
			break;
		case 2: start_t = clock();
				selectionSort(array1, size);	
				selectionSort(array2, size);	
				selectionSort(array3, size);	
				selectionSort(array4, size);	
				selectionSort(array5, size);	
				selectionSort(array6, size);	
				selectionSort(array7, size);	
				selectionSort(array8, size);	
				selectionSort(array9, size);	
				selectionSort(array10, size);	
				end_t = clock();
				time = (double)(end_t - start_t);
			break;
		case 3: start_t = clock();
				bubbleSort(array1, size);	
				bubbleSort(array2, size);	
				bubbleSort(array3, size);	
				bubbleSort(array4, size);	
				bubbleSort(array5, size);	
				bubbleSort(array6, size);	
				bubbleSort(array7, size);	
				bubbleSort(array8, size);	
				bubbleSort(array9, size);	
				bubbleSort(array10, size);	
				end_t = clock();
				time = (double)(end_t - start_t);
			break;
		case 4: start_t = clock();
				mergeSort(array1, 0, size);	
				mergeSort(array2, 0, size);	
				mergeSort(array3, 0, size);	
				mergeSort(array4, 0, size);	
				mergeSort(array5, 0, size);	
				mergeSort(array6, 0, size);	
				mergeSort(array7, 0, size);	
				mergeSort(array8, 0, size);	
				mergeSort(array9, 0, size);	
				mergeSort(array10, 0, size);	
				end_t = clock();
				time = (double)(end_t - start_t);
			break;
		case 5: start_t = clock();
				quickSort(array1, 0, size);	
				quickSort(array2, 0, size);	
				quickSort(array3, 0, size);	
				quickSort(array4, 0, size);	
				quickSort(array5, 0, size);	
				quickSort(array6, 0, size);	
				quickSort(array7, 0, size);	
				quickSort(array8, 0, size);	
				quickSort(array9, 0, size);	
				quickSort(array10, 0, size);	
				end_t = clock();
				time = (double)(end_t - start_t);
			break;
		default: puts("command not found");
	}

	return time / 10;
}
//NegaScout搜索函数
int NegaScout_TT_HH_Engine::negaScout(int depth, int alpha, int beta)
{
    int count,i;
    int type;
    int a,b,t;
    int side;
    int score;

    i = isGameOver(currentBoard, depth);        //游戏是否结束

    if(i != 0)
        return i;

    side=(maxDepth - depth) % 2;                         //计算当前节点的类型,极大 0/极小 1
    score = lookUpHashTable(alpha,beta,depth,side);     //查询哈希表中是否存在
    if(score!=66666)
        return score;
    if(depth <= 0)                                                 //叶子节点取估值
    {
        score = chessEvaluation->Eveluate(currentBoard,side);
        enterHashTable(exact,score,depth,side);                    //将估值存入置换表
        return score;
    }

    count = chessMoveGenerator->createAllPossibleMove(currentBoard,depth,side);  //产生左右走法

    for(i = 0;i < count;i++){
        chessMoveGenerator->moveList[depth][i].score =
                getHistoryScore(&chessMoveGenerator->moveList[depth][i]);       //得到某一走法的历史得分
    }

    mergeSort(chessMoveGenerator->moveList[depth],count,0);         //走法的历史得分排序

    int bestmove = -1;

    a = alpha;
    b = beta;

    int eval_is_exact=0;

    for(i=0;i<count;i++)
    {
        HashStepMove(&chessMoveGenerator->moveList[depth][i],currentBoard);

        type = stepMove(&chessMoveGenerator->moveList[depth][i]);

        t = -negaScout(depth-1,-b,-a);          //迭代搜索

        if(t>a && t<beta && i>0)
        {
            //对于第一个后的节点,如果上面的搜索 failhigh
            a = -negaScout(depth - 1,-beta,-t);                                /* re-search */
            eval_is_exact = 1;                                              //设数据类型为精确值
            if(depth == maxDepth)
                bestMove = chessMoveGenerator->moveList[depth][i];
            bestmove = i;
        }
        undoHashStepMove(&chessMoveGenerator->moveList[depth][i],type,currentBoard); //撤销哈希表操作
        undoStepMove(&chessMoveGenerator->moveList[depth][i],type);
        if(a < t)
        {
            eval_is_exact = 1;
            a = t;
            if(depth == maxDepth)
                bestMove = chessMoveGenerator->moveList[depth][i];
        }
        if(a >= beta)
        {
            enterHashTable(lower_bound,a,depth,side);
            enterHistoryScore(&chessMoveGenerator->moveList[depth][i],depth);
            return a;
        }
        b = a+1;
    }
    if(bestmove != -1)
        enterHistoryScore(&chessMoveGenerator->moveList[depth][bestmove], depth);
    if (eval_is_exact)
        enterHashTable(exact,a,depth,side);
    else
        enterHashTable(upper_bound,a,depth,side);
    return a;
}
예제 #5
0
struct arr * mergeSort(struct arr *merged,int size)
{
///    Split  	   
 	   if (size==1)
 		  return merged;

 	   int lsize,i,k,flag;
 	   struct arr *left,*right,*sleft,*sright,*temp;
   	   lsize=(size+1)/2;

	   temp=merged;
 	   for (i=1;i<lsize;i++)
 	   	   temp=temp->next;

       right=temp->next;
       temp->next=NULL;
   	   left=merged;
   	   	   
	   sleft=mergeSort(left,lsize);
	   sright=mergeSort(right,(size-lsize));


///	   Merge 
       flag=0;
	   
	   temp=malloc(sizeof(struct arr));
	   temp->next=NULL;
	   temp->value=0;
	   merged=temp;
	   long int counter=0;
	   for (i=1;i<size;i++)
	   {
	   	   insert(temp,0);
   		   if (flag==0)
		   {	   
		   		   if((sleft->value)<(sright->value))
			   	   {
					    temp->value=sleft->value;
					    temp=temp->next;
					    lsize--;
						if ((sleft->next)!=NULL)
						     sleft=sleft->next;
						else 
							 flag=1;
				   }
			   	   else
			   	   {
				   	    counter+=lsize;
					    temp->value=sright->value;
					    temp=temp->next;
						if ((sright->next)!=NULL)
						{
							sright=sright->next;
					    }	 
						else 
						{
							flag=2;
					    }
				   }
           }
   		   else if (flag==1)
		   {
		   		temp->value=sright->value;
		   		temp=temp->next;
		        sright=sright->next;
		   } 			   
   		   else if (flag==2)
		   {
		   		temp->value=sleft->value;
		   		temp=temp->next;
		   		sleft=sleft->next;		 				
		   }
	   }
	   
	   if (flag==1)
		   temp->value=sright->value;
	   else if (flag==2)
	   {
		   temp->value=sleft->value;		   
	   }	   
	return merged;	   
}	
예제 #6
0
/**
 * Sort elements of a stem variable as if it was an array.  This
 * routine assumes that element ".0" of the stem contains a size
 * value for the array portion of the elements, and that tail
 * indices ".start" to ".end", inclusive all exist in the tail.
 * Sorting will be performed on the string values of all elements,
 * and in the final result, all values will be replaced by the
 * string values.
 *
 * @param prefix
 * @param order
 * @param type
 * @param _first
 * @param last
 * @param firstcol
 * @param lastcol
 *
 * @return
 */
bool StemClass::sort(RexxString *prefix, int order, int type, size_t _first, size_t last, size_t firstcol, size_t lastcol)
{
    SortData sd;

    sd.startColumn = 0;
    sd.columnLength = 0;

    CompoundVariableTail stem_size(prefix, (size_t)0);
    CompoundTableElement *size_element = findCompoundVariable(stem_size);
    if (size_element == OREF_NULL)
    {
        return false;
    }
    RexxInternalObject *size_value = size_element->getVariableValue();
    if (size_value == OREF_NULL)
    {
        return false;
    }

    size_t count;
    // get the integer value of this.  It must be a valid numeric value.
    if (!size_value->unsignedNumberValue(count, Numerics::DEFAULT_DIGITS))
    {
        return false;
    }
    if (count == 0)         // if the count is zero, sorting is easy!
    {
        return true;
    }

    // if this is not specified, sort to the end
    if (last == SIZE_MAX)
    {
        last = count;
    }

    // verify we're fully within the bounds
    if (_first > count || last > count)
    {
        return false;
    }
    size_t bounds = last - _first + 1;

    // get an array item and protect it.  We need to have space for
    // the the variable anchors, the variable values, and a working buffer for the merge. */
    ArrayClass *array = new_array(bounds * 3);
    ProtectedObject p1(array);

    size_t i;
    size_t j;
    for (j = 1, i = _first; i <= last; i++, j++)
    {
        CompoundVariableTail nextStem(prefix, (size_t)i);
        CompoundTableElement *next_element = findCompoundVariable(nextStem);

        if (next_element == OREF_NULL) {
            return false;
        }

        RexxInternalObject *nextValue = next_element->getVariableValue();
        if (nextValue == OREF_NULL)
        {
            return false;
        }
        // force this to a string value.
        nextValue = nextValue->requestString();
        // now anchor both in the sorting array
        array->put(next_element, j);
        array->put(nextValue, j + bounds);
    }

    // the data to be sorted
    RexxString **aData = (RexxString **)array->data(bounds + 1);
    // the merge sort work area
    RexxString **working = (RexxString **)array->data((bounds * 2) + 1);

    {
        // we're releasing kernel access during the process.  The sort is being
        // done on a locally allocated array, so this will not be accessed by another thread.
        // All the rest of the operations are thread safe.
        UnsafeBlock block;

        if ((firstcol == 0) && (lastcol == SIZE_MAX))
        {
            /* no special columns to check */
            switch (type)
            {
                case SORT_CASESENSITIVE:
                    mergeSort(&sd, order == SORT_ASCENDING ? compare_asc : compare_desc,
                        aData, working, 0, bounds - 1);
                    break;
                case SORT_CASEIGNORE:
                    mergeSort(&sd, order == SORT_ASCENDING ? compare_asc_i : compare_desc_i,
                        aData, working, 0, bounds - 1);
                  break;
            }
        }
        else
        {
            /* set columns to sort */
            sd.startColumn = firstcol;
            sd.columnLength = lastcol - firstcol + 1;

            switch (type)
            {
              case SORT_CASESENSITIVE:
                  mergeSort(&sd, order == SORT_ASCENDING ? compare_asc_cols : compare_desc_cols,
                      aData, working, 0, bounds - 1);
                  break;
              case SORT_CASEIGNORE:
                  mergeSort(&sd, order == SORT_ASCENDING ? compare_asc_i_cols : compare_desc_i_cols,
                      aData, working, 0, bounds - 1);
                  break;
            }
        }
    }


    /* The values have now been sorted.  We now need to set each */
    /* each variable back to its new value. */
    for (i = 1; i <= bounds; i++)
    {
        CompoundTableElement *element = (CompoundTableElement *)array->get(i);
        RexxObject *_value = (RexxObject *)array->get(i + bounds);
        element->set(_value);
    }
    return true;
}
예제 #7
0
//****自定义绘图函数*********************************
// 1.对窗口中跑动的恐龙进行排序贴图
// 2.恐龙贴图坐标修正
void MyPaint(HDC hdc)
{
	int w, h, i;

	clockRecord = clock();						// 记录每帧起始时间

	if (picNum == 8)
		picNum = 0;

	//在mdc中先贴上背景图
	SelectObject(bufdc, bg);
	BitBlt(mdc, 0, 0, 640, 480, bufdc, 0, 0, SRCCOPY);

	// 贴上恐龙图之前调用BubSort()函数进行排序
	// 选择排序算法
	// 可以明显看出两个排序算法——起泡排序和归并排序——的效率差距
	switch (sortMethod)
	{
	case 0:
		mergeSort(dra);
		break;

	default:
		BubSort(draNum);
		break;
	}
	
	//下面这个for循环,按照目前恐龙的移动方向dra[i].dir,
	//选取对应的位图到bufdc中,并设定截切的大小。
	//每一张要在窗口上出现的恐龙图案依次先在mdc上进行透明贴图的操作。
	for (i = 0; i < draNum; i++)
	{
		SelectObject(bufdc, draPic[dra[i].Dir()]);
		switch (dra[i].Dir())
		{
		case 0:
			w = 66;
			h = 94;
			break;
		case 1:
			w = 68;
			h = 82;
			break;
		case 2:
			w = 95;
			h = 99;
			break;
		case 3:
			w = 95;
			h = 99;
			break;
		}
		BitBlt(mdc, (int)dra[i].X(), (int)dra[i].Y(), w, h, bufdc, picNum*w, h, SRCAND);
		BitBlt(mdc, (int)dra[i].X(), (int)dra[i].Y(), w, h, bufdc, picNum*w, 0, SRCPAINT);
	}

	//将最后画面显示在窗口中
	BitBlt(hdc, 0, 0, 640, 480, mdc, 0, 0, SRCCOPY);

	tPre = GetTickCount();         //记录此次绘图时间
	picNum++;


	//下面这个for循环,决定每一只恐龙下一次的移动方向及贴图坐标
	for (i = 0; i < draNum; i++)
	{
		dra[i].update();
		/*
		//随机数除以4的余数来决定下次移动方向,余数0,1,2,3分别代表上,下,左,右
		switch (rand() % 4)          
		{
		//case 0里面的代码,按照目前的移动方向来修正因为各个方向图案尺寸不一致而产生的贴图坐标误差,
		//加入恐龙每次移动的单位量(上,下,左,右每次20个单位)而得到下次新的贴图坐标
		case 0:					     //上
		switch (dra[i].Dir())
		{
		case 0:
		dra[i].Y(dra[i].Y() - 20);
		break;
		case 1:
		dra[i].X(dra[i].X() + 2);
		dra[i].Y(dra[i].Y() - 31);
		break;
		case 2:
		dra[i].X(dra[i].X() + 14);
		dra[i].Y(dra[i].Y() - 31);
		break;
		case 3:
		dra[i].X(dra[i].X() + 14);
		dra[i].Y(dra[i].Y() - 20);
		break;
		}
		//在计算出新的贴图坐标之后,还需判断此新的坐标会不会使得恐龙贴图超出窗口边界,
		//若超出,则将该方向上的坐标设定为刚好等于临界值
		if (dra[i].Y() < 0)
		dra[i].Y(0);
		dra[i].Dir(0);
		break;
		//其他方向按照和上面相同的方法计算
		case 1:				     	//下
		switch (dra[i].Dir())
		{
		case 0:
		dra[i].X(dra[i].X() - 2);
		dra[i].Y(dra[i].Y() + 31);
		break;
		case 1:
		dra[i].Y(dra[i].Y() + 20);
		break;
		case 2:
		dra[i].X(dra[i].X() + 15);
		dra[i].Y(dra[i].Y() + 29);
		break;
		case 3:
		dra[i].X(dra[i].X() + 15);
		dra[i].Y(dra[i].Y() + 29);
		break;
		}

		if (dra[i].Y() > 370)
		dra[i].Y(370);
		dra[i].Dir(1);
		break;
		case 2:				    	//左
		switch (dra[i].Dir())
		{
		case 0:
		dra[i].X(dra[i].X() - 34);
		break;
		case 1:
		dra[i].X(dra[i].X() - 34);
		dra[i].Y(dra[i].Y() - 9);
		break;
		case 2:
		dra[i].X(dra[i].X() - 20);
		break;
		case 3:
		dra[i].X(dra[i].X() - 20);
		break;
		}
		if (dra[i].X() < 0)
		dra[i].X(0);
		dra[i].Dir(2);
		break;
		case 3:				    	//右
		switch (dra[i].Dir())
		{
		case 0:
		dra[i].X(dra[i].X() + 6);
		break;
		case 1:
		dra[i].X(dra[i].X() + 6);
		dra[i].Y(dra[i].Y() - 10);
		break;
		case 2:
		dra[i].X(dra[i].X() + 20);
		break;
		case 3:
		dra[i].X(dra[i].X() + 20);
		break;
		}
		if (dra[i].X() > 535)
		dra[i].X(535);
		dra[i].Dir(3);
		break;
		}
		*/
	}

	cout << "每帧刷新时间:\t" << (clockRecord - clock()) << endl;
}
LinkedListNode * LinkedListSort::sort(LinkedListNode * list){
	mergeSort(&list);
	return list;
}
예제 #9
0
void bspParSort(){

  int Log2(int x);
  void mergeSort(int x, int *temp1);
  void merge2(int *arr1, int *arr2, int size);

  int *localArr; /* local array in each processor */
  int i,j,k; /* index variables */
  int n_divide_p; /* Avoid multiple computation */
  int n; /* Number of elements to be sorted */
  int szLocalArray; /* Size of local array */
  double time0, time1; /* Time */
  FILE *ifp = 0; /* Reader to read sequence of numbers to be sorted */

  bsp_begin(P);
  int p= bsp_nprocs(); /* Number of processors obtained */ 
  int s= bsp_pid();    /* Processor number */ 

  //Get number of elements to be sorted
  if(s==0){
    ifp = fopen("sort","r");
    if(ifp == NULL){
      fprintf(stderr, "Can't open input file!\n");
      exit(1);
    }
    fscanf(ifp, "%i", &n);
  }

  // Make sure every processor knows everything
  bsp_push_reg(&n,sizeof(int));
  bsp_sync();
  bsp_get(0,&n,0,&n,sizeof(int));
  bsp_sync();
  bsp_pop_reg(&n);

  //Setup distribution 
  n_divide_p = n/p;
  szLocalArray = n/pow(2,ceil(Log2(s+1)));
  localArr = vecalloci(szLocalArray);
  bsp_push_reg(localArr,sizeof(int)*szLocalArray);

  if(s==0){ 
    printf("Distribution start\n"); fflush(stdout); 
  }

  bsp_sync();
  int value;
  if(s==0){
    //allocate to array on proc 0
    for(i=0; i< n_divide_p; i++){
      fscanf(ifp, "%i", &value);
      localArr[i]=value;      
    }
    //Send to arrays on other processors
    for(i=1; i< p; i++){
      for(j=0;j<n_divide_p;j++){
        fscanf(ifp, "%i", &value);
        bsp_put(i,&value,localArr,j*sizeof(int),sizeof(int));
      }
    }
    fclose(ifp);
  }
  bsp_sync();
  if(s==0){ 
    printf("Distribution done\n"); fflush(stdout); 
  }

  //Distribution done and we can start time measurement 
  if(s==0){
    printf("Time start\n"); fflush(stdout);
  }
  time0 = bsp_time();

  //Locally sort each array
  if(s==0){
    printf("Local sort\n"); fflush(stdout);
  }
  mergeSort(n_divide_p, localArr);
  bsp_sync();

  //Merging 
  int *temp = malloc(sizeof(int)*pow(2,Log2(p))*n_divide_p);
  for(j=1;j<Log2(p)+1;j++){
    if(s<p/pow(2,j)){
      for(k=0;k<pow(2,j-1)*n_divide_p;k++){
        bsp_get(s+(p/pow(2,j)),localArr,k*sizeof(int),&(temp[k]),sizeof(int));
      }
    }
    bsp_sync();

    if(s<p/pow(2,j)){
      merge2(localArr, temp, n_divide_p*pow(2,j-1));
    }

    bsp_sync();
    if(s==0){ 
      printf("Round %i out of %i rounds of merging done (on proc 0)\n",j,Log2(p)); fflush(stdout); 
    }
  }
  if(s==0){
    printf("Sorting done\n"); fflush(stdout);
  }
  bsp_sync();
 
  //Print sorted array - expensive if sample is big
  /*
  if(s==0){
    printf("Sorted sequence is:\n");
    for(i=0; i<szLocalArray; i++){
      printf("%i ",localArr[i]); fflush(stdout);
    }
    printf("\n"); fflush(stdout);
  }
  */

  //Parallel algorithm ends
  time1 = bsp_time();
  if(s==0){
    printf("Time stop\n"); fflush(stdout);
  }

  //Report time to user
  if(s==0){
    printf("Sorting took %.6lf seconds.\n", time1-time0); fflush(stdout);
  }
  
  //Clean up
  free(temp);
  bsp_pop_reg(localArr); free(localArr);

  bsp_end();
} /* End bspParSort */
예제 #10
0
int compare_sort(int *array, int size){
    //Split and reverse the array
    
    int array1_size = size/2;
    int array1[array1_size];
    for(int i = 0; i < size/2; i++){
        array1[i] = array[i];
    }
    int j = 0;
    int array2_size = size - size/2;
    int array2[array2_size];
    for(int i = size/2; i < size; i++){
        array2[j] = -array[i];
        j++;
    }
    
    int array2rev[array2_size];
    
    for(int t=1; t<=array2_size; t++){
        array2rev[t-1] = array2[array2_size-t];
    }
    
    int totalsize = array1_size + array2_size;
    
    //Compute sum arrays
    //Dump positive array 1 sums into first half of sumarray
    arraymeta *sumarray = malloc(totalsize * sizeof(arraymeta));
    j = 0; //index for sumarray
    int tempsum = 0;
    for (int i=array1_size-1; i >= 0; i--){
        tempsum += array1[i];
        sumarray[j].value = tempsum;
        sumarray[j].parent_array = 1;
        j++;
    }
    tempsum = 0;
    //Dump negative array 2 sums into second half of sumarray
    for (int i=array2_size-1; i >= 0; i--){
        tempsum += array2[i];
        sumarray[j].value = tempsum;
        sumarray[j].parent_array = 2;
        j++;
    }
    
    arraymeta temp[totalsize];
    
    mergeSort(sumarray, temp, totalsize);
    
    arraydiff smallestdiff, tempdiff;
    
    //These will invert the number if it's in the negative array
    int inversion1 = 1;
    int inversion2 = 1;
    
    //Initial case
    int i = 0;
    while(sumarray[i].parent_array == sumarray[i+1].parent_array){
        i++;
    }
    if(sumarray[i].parent_array != sumarray[i+1].parent_array){
        if(sumarray[i].parent_array == 2){
            inversion1 = -1;
        } else if(sumarray[i+1].parent_array == 2){
            inversion2 = -1;
        }
        smallestdiff.value = inversion1 * sumarray[i].value + inversion2 * sumarray[i+1].value;
        smallestdiff.lower_bound = inversion1 * sumarray[i].value;
        smallestdiff.upper_bound = inversion2 * sumarray[i+1].value;
    }
    for(i; i < totalsize; i++){
        if(sumarray[i].parent_array != sumarray[i+1].parent_array){
            inversion1 = inversion2 = 1; //Reset
            if(sumarray[i].parent_array == 2){
                inversion1 = -1;
            } else if(sumarray[i+1].parent_array == 2){
                inversion2 = -1;
            }
            tempdiff.value = inversion1 * sumarray[i].value + inversion2 * sumarray[i+1].value;
            if(abs(tempdiff.value) < abs(smallestdiff.value)){
                smallestdiff.value = tempdiff.value;
                smallestdiff.lower_bound = inversion1 * sumarray[i].value;
                smallestdiff.upper_bound = inversion2 * sumarray[i+1].value;
            }
        }
    }
    //Compare this with the sums within the arrays
    int tempsum1, tempsum2;
    tempsum1 = tempsum2 = 0;
    for(i = 0; i < array1_size; i++){
        tempsum1 += array1[i];
    }
    
    for(i = 0; i < array2_size; i++){
        tempsum2 += array2[i];
    }
    return lesser_of(lesser_of(smallestdiff.value, tempsum1), tempsum2);
}
예제 #11
0
 ListNode* sortList(ListNode* head) {
     return mergeSort(head);
 }
예제 #12
0
파일: model.c 프로젝트: devaib/cnn
int main(void){

    // minimum size(pixels) of detection object (multiple of 12)
    const int MinFaceSize = 72;

    // thresholds
    const float Threshold_12Layer = .5;
    const float Threshold_24Layer = .01;
    const float Threshold_48Layer = -.01;
    const float Threshold_12CalibrationLayer = .1;
    const float Threshold_24CalibrationLayer = .1;
    const float Threshold_48CalibrationLayer = .1;
    const float Threshold_12NMS = .3f;
    const float Threshold_24NMS = .3f;
    const float Threshold_48NMS = 1.0f;

    // detection windows
    struct Windows window[500];

    // loop counter
    int i, j, k;
    int row, col;
    int counter = 0;    // detection window counter

    // image information
    int height, width, step, channels;
    uchar *data, *data24, *data48;

    // size, x, y for calibration
    float *out_12c, *out_24c, *out_48c;     // vector carrying s,x,y
    float s, x, y;
    int cali_x, cali_y, cali_w, cali_h;

    // scores of the 12 layer
    float res_12Layer;
    float res_24Layer;
    float res_48Layer;

    // window sliding stride
    const int Stride = 4;

    // image pyramid rate
    int pyr_rate = MinFaceSize / 12;

    // image pyrimid stopping
    bool flagStop = false;

    // file path
    char file[150];
    strcpy(file, FILE_PATH);
    strcat(file, TEST_IMAGE);

    // alloc memory for 12x12 image
    float **img = malloc(12 * sizeof(float*));
    for (i = 0; i < 12; i++){
        img[i] = malloc(12 * sizeof(float));
    }

    // alloc memory for 24x24 image
    float **img24 = malloc(24 * sizeof(float*));
    for (i = 0; i < 24; i++){
        img24[i] = malloc(24 * sizeof(float));
    }

    // alloc memory for 48x48 image
    float **img48 = malloc(48 * sizeof(float*));
    for (i = 0; i < 48; i++){
        img48[i] = malloc(48 * sizeof(float));
    }

    // for printing scores
    CvFont font;
    cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.3, 0.3, 0, 1, 8);
    char word[5];

    // load image
    IplImage *srcImg, *dstImg;
    srcImg = cvLoadImage(file, CV_LOAD_IMAGE_GRAYSCALE);

    // original size of the image
    const int WIDTH = srcImg->width;
    const int HEIGHT = srcImg->height;

    IplImage *originImg = cvCloneImage(srcImg);
    IplImage *originImg1 = cvCloneImage(srcImg);
    IplImage *originImg2 = cvCloneImage(srcImg);
    IplImage *originImg3 = cvCloneImage(srcImg);
    IplImage *input24Img = cvCreateImage(cvSize(24, 24), IPL_DEPTH_8U, 1);
    IplImage *input48Img = cvCreateImage(cvSize(48, 48), IPL_DEPTH_8U, 1);

    if (!srcImg){
        printf("Could not load image file: %s\n", file);
        exit(1);
    }


    // image pyramid loop starts
    while (!flagStop){
        counter = 0;

        // image pyramid down
        dstImg = doPyrDown(srcImg, pyr_rate);


        // get the image data
        width = dstImg -> width;
        height = dstImg -> height;
        step = dstImg -> widthStep;
        channels = dstImg -> nChannels;
        data = (uchar*)dstImg -> imageData;

        IplImage *detectedImg_12Layer = cvCloneImage(dstImg);

        // window sliding loop starts
        for (row = 0; row + 12 <= height; row += Stride){
            for (col = 0; col + 12 <= width; col += Stride){
                // 12 layer, 12 calibration, NMS
                preprocess(img, data, row, col, step, channels, 12);

                res_12Layer = Layer12(img, 12, 12, channels);

                // 12 layer passed
                if (res_12Layer > Threshold_12Layer){
                    // 12 calibration layer
                    out_12c = CaliLayer12(img, 12, 12, channels, Threshold_12CalibrationLayer);

                    s = out_12c[0]; x = out_12c[1]; y = out_12c[2];
                    free(out_12c);      // memory allocated in CaliLayer12

                    // ignoring returned NAN values(comparison involving them are always false)
                    if (s != s || x != x || y != y) continue;

                    // calibration
                    cali_x = col * pyr_rate - x * 12 * pyr_rate / s;
                    cali_y = row * pyr_rate - y * 12 * pyr_rate / s;
                    cali_w = 12 * pyr_rate / s;
                    cali_h = 12 * pyr_rate / s;

                    // make sure the calibrated window not beyond the image boundary
                    if (cali_x >= WIDTH || cali_y >= HEIGHT) continue;

                    cali_x = max(cali_x, 0);
                    cali_y = max(cali_y, 0);
                    cali_w = min(cali_w, WIDTH - cali_x);
                    cali_h = min(cali_h, HEIGHT - cali_y);

                    window[counter].x1 = cali_x;                    // x1
                    window[counter].y1 = cali_y;                    // y1
                    window[counter].x2 = cali_x + cali_w;           // x2
                    window[counter].y2 = cali_y + cali_h;           // y2
                    window[counter].score = res_12Layer;            // 12 layer score
                    window[counter].iou = 0.0;                      // iou ratio
                    window[counter].dropped= false;                 // if it's dropped
                    counter++;
                    // end of 12 layer, 12 calibration


                }
            }
        }
        // window sliding loop ends

        // sort the detection windows by score in descending order
        mergeSort(window, 0, counter);

        // display sorted windows surviving 12 layer
        cvNamedWindow("12 layer", CV_WINDOW_AUTOSIZE);
        for (i = 0; i < counter; i++){
            cvRectangle(originImg, cvPoint(window[i].x1, window[i].y1), cvPoint(window[i].x2, window[i].y2), cvScalar(255,0,0,0), 2, 4, 0);
            // printf("[#%d] x1: %d, y1: %d, x2: %d, y2: %d, score: %f, iou: %f, dropped: %s\n", i, window[i].x1, window[i].y1, window[i].x2, window[i].y2, window[i].score, window[i].iou, window[i].dropped ? "true" : "false");

            if (window[i].dropped == false){
                sprintf(word, "%.2f", window[i].score);
                cvPutText(originImg, word, cvPoint(window[i].x1, window[i].y1), &font, cvScalar(255, 255, 255, 0));
            }
        }
        cvShowImage("12 layer", originImg);
        cvMoveWindow("12 layer", 10, 10);

        printf("12 layer: x1: %d, y1: %d, x2: %d, y2: %d\n", window[15].x1, window[15].y1, window[15].x2, window[15].y2);

        // NMS after 12 calibration
        nms(window, counter, Threshold_12NMS);

        // display sorted windows surviving 12 layer
        cvNamedWindow("12 layer after NMS", CV_WINDOW_AUTOSIZE);
        for (i = 0; i < counter; i++){
            if (window[i].dropped == false){
                cvRectangle(originImg1, cvPoint(window[i].x1, window[i].y1), cvPoint(window[i].x2, window[i].y2), cvScalar(255,0,0,0), 2, 4, 0);

                sprintf(word, "%.2f", window[i].score);
                cvPutText(originImg1, word, cvPoint(window[i].x1, window[i].y1), &font, cvScalar(255, 255, 255, 0));
            }
        }
        cvShowImage("12 layer after NMS", originImg1);
        cvMoveWindow("12 layer after NMS", 500, 10);

        // 24 layer, 24 calibration, NMS
        for (i = 0; i< counter; i++){
            if (window[i].dropped == true) continue;

            cvSetImageROI(srcImg, cvRect(window[i].x1, window[i].y1, window[i].x2 - window[i].x1, window[i].y2 - window[i].y1));
            cvResize(srcImg, input24Img, CV_INTER_AREA);

            data24 = (uchar*) input24Img->imageData;

            preprocess(img24, data24, 0, 0, input24Img->widthStep, input24Img->nChannels, 24);
            res_24Layer = Layer24(img24, 24, 24, input24Img->nChannels);

            // 24 layer passed
            if (res_24Layer > Threshold_24Layer){
                // 24 calibration
                out_24c = CaliLayer24(img24, 24, 24, input24Img->nChannels, Threshold_24CalibrationLayer);
                s = out_24c[0];
                x = out_24c[1];
                y = out_24c[2];
                free(out_24c);

                cali_x = window[i].x1 - x * (window[i].x2 - window[i].x1) / s;
                cali_y = window[i].y1 - y * (window[i].y2 - window[i].y1) / s;
                cali_w = (window[i].x2 - window[i].x1) / s;
                cali_h = (window[i].y2 - window[i].y1) / s;

                // make sure the calibrated window not beyond the image boundary
                if (cali_x >= WIDTH || cali_y >= HEIGHT) continue;

                cali_x = max(cali_x, 0);
                cali_y = max(cali_y, 0);
                cali_w = min(cali_w, WIDTH - cali_x);
                cali_h = min(cali_h, HEIGHT - cali_y);

                window[i].x1 = cali_x;                    // x1
                window[i].y1 = cali_y;                    // y1
                window[i].x2 = cali_x + cali_w;           // x2
                window[i].y2 = cali_y + cali_h;           // y2
                window[i].score = res_24Layer;            // 24 layer score
                window[i].iou = 0.0;                      // iou ratio
                window[i].dropped= false;                 // if it's dropped

            }
            else
            {
                window[i].dropped = true;
            }

            cvResetImageROI(srcImg);
        }

        printf("24 layer: x1: %d, y1: %d, x2: %d, y2: %d\n", window[15].x1, window[15].y1, window[15].x2, window[15].y2);

        // NMS after 24 calibration
        nms(window, counter, Threshold_24NMS);

        // display sorted windows surviving 24 layer
        cvNamedWindow("24 layer", CV_WINDOW_AUTOSIZE);
        for (i = 0; i < counter; i++){
            if (window[i].dropped == false){
                cvRectangle(originImg2, cvPoint(window[i].x1, window[i].y1), cvPoint(window[i].x2, window[i].y2), cvScalar(255,0,0,0), 2, 4, 0);

                sprintf(word, "%.2f", window[i].score);
                cvPutText(originImg2, word, cvPoint(window[i].x1, window[i].y1), &font, cvScalar(255, 255, 255, 0));
            }
        }
        cvShowImage("24 layer", originImg2);
        cvMoveWindow("24 layer", 10, 400);
        // end of 24 layer, 24 calibration, NMS


        // 48 layer, 48 calibration, NMS
        for (i = 0; i< counter; i++){
            if (window[i].dropped == true) continue;

            cvSetImageROI(srcImg, cvRect(window[i].x1, window[i].y1, window[i].x2 - window[i].x1, window[i].y2 - window[i].y1));
            cvResize(srcImg, input48Img, CV_INTER_AREA);

            data48 = (uchar*) input48Img->imageData;

            preprocess(img48, data48, 0, 0, input48Img->widthStep, input48Img->nChannels, 48);
            res_48Layer = Layer48(img48, 48, 48, input48Img->nChannels);

            // 48 layer passed
            if (res_48Layer > Threshold_48Layer){
                // 48 calibration
                out_48c = CaliLayer48(img48, 48, 48, input48Img->nChannels, Threshold_48CalibrationLayer);

                s = out_48c[0];
                x = out_48c[1];
                y = out_48c[2];
                free(out_48c);

                cali_x = window[i].x1 - x * (window[i].x2 - window[i].x1) / s;
                cali_y = window[i].y1 - y * (window[i].y2 - window[i].y1) / s;
                cali_w = (window[i].x2 - window[i].x1) / s;
                cali_h = (window[i].y2 - window[i].y1) / s;

                // make sure the calibrated window not beyond the image boundary
                if (cali_x >= WIDTH || cali_y >= HEIGHT) window[i].dropped = true;

                cali_x = max(cali_x, 0);
                cali_y = max(cali_y, 0);
                cali_w = min(cali_w, WIDTH - cali_x);
                cali_h = min(cali_h, HEIGHT - cali_y);

                window[i].x1 = cali_x;                    // x1
                window[i].y1 = cali_y;                    // y1
                window[i].x2 = cali_x + cali_w;           // x2
                window[i].y2 = cali_y + cali_h;           // y2
                window[i].score = res_48Layer;            // 48 layer score
                window[i].iou = 0.0;                      // iou ratio
                window[i].dropped= false;                 // if it's dropped
            }
            else
            {
                window[i].dropped = true;
            }

            cvResetImageROI(srcImg);
        }

        // NMS after 48 calibration
        nms(window, counter, Threshold_48NMS);

        // display sorted windows surviving 48 layer
        cvNamedWindow("48 layer", CV_WINDOW_AUTOSIZE);
        for (i = 0; i < counter; i++){
            if (window[i].dropped == false){
                cvRectangle(originImg3, cvPoint(window[i].x1, window[i].y1), cvPoint(window[i].x2, window[i].y2), cvScalar(255,0,0,0), 2, 4, 0);

                sprintf(word, "%.2f", window[i].score);
                cvPutText(originImg3, word, cvPoint(window[i].x1, window[i].y1), &font, cvScalar(255, 255, 255, 0));
            }
        }
        cvShowImage("48 layer", originImg3);
        cvMoveWindow("48 layer", 500, 400);
        // end of 48 layer, 48 calibration, NMS

        printf("48 layer: x1: %d, y1: %d, x2: %d, y2: %d, dropped: %s\n", window[15].x1, window[15].y1, window[15].x2, window[15].y2, window[15].dropped?"true":"false");







        cvWaitKey(0);
        cvDestroyWindow("12 layer");
        cvDestroyWindow("12 layer after NMS");
        cvDestroyWindow("24 layer");
        cvDestroyWindow("48 layer");

        pyr_rate *= 2;
        if (dstImg->height / 2 < 12) flagStop = true;
    }
    // image pyramid loop ends

    freeArray(img, 12);
    freeArray(img24, 12);
    freeArray(img48, 12);

    return 0;
}
예제 #13
0
//to sort in the standard of cmp with method of mergeSort
void list_sort(list *plist, cmp_t cmp){
	mergeSort(list_begin(plist), list_end(plist), plist->m_size, cmp);
}
예제 #14
0
int main() 
{
    const unsigned long int N = 100;
    
    std::cout << N << std::endl;

    srand((int) time(NULL));
    
    int * a = new int[N];
    int * aux = new int[N];

    copiaNumeros(a,N);
    
    for (int i = 0; i < N; ++i) 
    {
        aux[i] = a[i];
    }

    auto begin = std::chrono::high_resolution_clock::now();
    bubbleSort(a, N);
    auto end = std::chrono::high_resolution_clock::now();
    auto tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Bubble: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    cocktailSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Cocktail: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    insertionSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Insertion: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    bucketSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Bucket: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    countingSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Counting: "<<tiempo.count()<<std::endl;

    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    mergeSort(a, 0, N-1, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Merge: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    radixSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Radix: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    shellSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Shell: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    selectionSort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Selection: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    quickSort(a, 0, N-1);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Quick: "<<tiempo.count()<<std::endl;
    
    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    heap_sort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Heap: "<<tiempo.count()<<std::endl;

    for( int i = 0; i<N; i++)
    {
        a[i] = aux[i];
    }
    begin = std::chrono::high_resolution_clock::now();
    binarySort(a, N);
    end = std::chrono::high_resolution_clock::now();
    tiempo = std::chrono::duration_cast<std::chrono::microseconds>(end-begin);
    std::cout<<"Binary: "<<tiempo.count()<<std::endl;

    delete a;
    delete aux;

    return 0;
}
예제 #15
0
파일: files.c 프로젝트: Yunnii/OS
int main(int argc,char **argv)
{
	if(argc<3)
	{
		printf("Too less parametrs.In and out files \n");
		exit(1);
	}
	FILE *handle=0;
	int	fnumb=argc-2;
	int	temp;
	int	schital;
	int ErrNum=0;
	struct dinmas sortmas={0,10,0};
	sortmas.mas=(int*)malloc(sortmas.maxlength*sizeof(int));
	if (sortmas.mas==NULL)
	{
		printf("Not avaliable memory for creating membuf");
		exit(1);
	}
	for( ; ErrNum==0 && fnumb!=0 && (handle=fopen(argv[fnumb],"r"));fnumb--)
	{
		while(EOF!=(schital=fscanf(handle,"%d",&temp)))
		{
			if(schital==0)
			{
				ErrNum=1;
				break;
			}
			if(sortmas.length==sortmas.maxlength)
			{
				sortmas.maxlength*=2;
				int *tempmas=(int*)realloc(sortmas.mas,sortmas.maxlength);
				if (tempmas==NULL)
				{
					ErrNum=2;
					break;
				}
				sortmas.mas=tempmas;
			}
			sortmas.mas[sortmas.length]=temp;
			sortmas.length++;
		}
		fclose(handle);
	}
	if(fnumb!=0 && ErrNum==0)
		ErrNum=3;
	if (ErrNum==0)
	//sortirovka(&sortmas);
		if (mergeSort(&sortmas,0,sortmas.length)==0)
			if(handle=fopen(argv[argc-1],"w"))
			{
				for(int i=0;i<sortmas.length;i++)
					fprintf(handle,"%d\n",sortmas.mas[i]);
				fclose(handle);
			}
			else	ErrNum=4;
	free(sortmas.mas);

	switch(ErrNum)
	{
		case 1:
			printf("Error input file format %s",argv[fnumb+1]);
			break;
		case 2:
			printf("Not avalliable free memory");
			break;
		case 3:
			printf("Can't open file %s",argv[fnumb]);
			break;
		case 4:
			printf("Can't open output file %s", argv[argc-1]);
		case 0:
			break;
	}
	return	0;
}
예제 #16
0
파일: main.c 프로젝트: WDayan/LastWork
int main(){
	
	int fn,size;
	TpContato *tp = start();
	ListaContato *lista = init(), *lista_copy=init(), *lista_aux=init();
	TpContato *aux = start(), *copy = aux;

	clock_t cinicio, cfinal;
	
	system("clear");
	do{
		printf(
			"Escolha uma das opções abaixo:\n"
			"\t1) Criar Lista\n"
			"\t2) Cirar Vetor\n"
			"\t3) Ordenacao com Comb Sort\n"
			"\t4) Ordenacao com Merge Sort\n"
			"\t5) Sair\n\n"
		);

		scanf(" %d",&fn);
		switch(fn){
			case 1:
				system("clear");
				printf("Criar lista com quantos elementos?\n");
				scanf(" %d", &size);
				lista = createLista(size);
				printLista(lista);
				break;
			case 2:
				system("clear");
				printf("\t2) Cirar Vetor\n");

				tp = createVetor();
				fillVetor(tp);
				printVetor(tp);

				break;
			case 3:
				system("clear");
				printf("\t3) Ordenacao com Comb Sort\n");

				if (!isEmpty_vetor(tp)){
					copy = createVetor();
					vetcpy(copy, tp);

					cinicio = clock();
					combSort_vetor(copy);
					cfinal = clock();
					printf("\n");
					printVetor(copy);
					printf("Tempo: %f segundos.\n", (float)(cfinal-cinicio)/CLOCKS_PER_SEC);

					if(!isEmpty_vetor(copy)) free(copy);
				}
				if (!isEmpty_lista(lista)){
					lista_copy = listacpy(lista);

					cinicio = clock();
					combSort_lista(lista_copy,size);
					cfinal = clock();
					printf("\n");
					printLista(lista_copy);
					printf("Tempo: %f segundos.\n", (float)(cfinal-cinicio)/CLOCKS_PER_SEC);

					lista_copy = ourFree(lista_copy);
				}

				break;
			case 4:
				system("clear");
				printf("\t4) Ordenacao com Merge Sort\n");

				if (!isEmpty_vetor(tp)){
					aux = createVetor();
					copy = createVetor();
					vetcpy(copy, tp);

					cinicio = clock();
					mergeSort(copy, 0, MAX-1, aux);	// Vetor vai de 0-39
					cfinal = clock();

					printf("\n");
					printVetor(copy);
					printf("Tempo: %f segundos.\n", (float)(cfinal-cinicio)/CLOCKS_PER_SEC);

					if (!isEmpty_vetor(aux)) free(aux); 	// Liberando memória
					if (!isEmpty_vetor(copy)) free(copy); 	// Liberando memória
				}

				if (!isEmpty_lista(lista)){
					lista_copy = listacpy(lista);

					cinicio = clock();
					lista_aux = mergeSortList(lista_copy, 0, size-1, lista_aux);	
					cfinal = clock();

					printf("\n");
					printLista(lista_copy);
					printf("Tempo: %f segundos.\n", (float)(cfinal-cinicio)/CLOCKS_PER_SEC);
					
					lista_copy = ourFree(lista_copy);
					lista_aux = ourFree(lista_aux);

				}
				break;
			case 5:
				system("clear");
				printf("BYE!\n\n");
				break;
			default:
				system("clear");
				printf("Opção invalida!\n");
				break;
		}
	}while(fn != 5);

	if (!isEmpty_vetor(tp)) free(tp);

	lista = ourFree(lista);
	
	return 0;
}
예제 #17
0
파일: problema1.c 프로젝트: bcsaldias/eddC
int solution(int A[], int N){
	/*
		El problema se consideró como intersección entre
		intervalos en el eje X. Es decir, se calculan las
		intersecciones solo en el eje X. El problema se
		reduce a intersección de intervalos más que a 
		intersección de discos en el espacio, ya que sabemos
		que todos tienen su coordenada Y en 0.
	*/

	/*
	En el array posiciones se guardará:
	posiciones[i][0] 	= 	i - radio[i] ó i + radio[i], es decir,
			 				guarda el inicios y final del disco i.
	posiciones[i][1]	= 	guarda un 0 si es en A[i][0] hay un inicio,
			  				guarda un 1 si hay un final.
	posiciones[i][2]	=	guarda el centro del disco, es decir, su id.
	*/

	int posiciones[N*2][3];
	int temp[N*2][3];

	/*
	Inicialización de 'posiciones'
	*/
	for (int i = 0; i < N; i+=1)
	{
		posiciones[i][0] = i-A[i];
		posiciones[N + i][0] = i+A[i];
		posiciones[i][1] = 0;
		posiciones[N + i][1] = 1;
		posiciones[i][2] = i;
		posiciones[N + i][2] = i;

		temp[i][0] = 0;
		temp[N + i][0] = 0;
		temp[i][1] = 0;
		temp[N + i][1] = 0;
		temp[i][2] = 0;
		temp[N + i][2] = 0;
	}

	/*
	El primer lugar se ordenan de acuerdo a si son 
	puntos de inicio o fin, quedando así todos los 
	inicios de discos primero en el arreglo que los
	finales.
	*/
	mergeSort(posiciones, temp, 0, 2*N-1, 1);

	/*
	Luego se ordenan correlativamente los valores 
	de los inicios y finales, es decir, los valores 
	de posiciones[i][0]. Debido a que anteriormente
	fueron ordenados por tipo inicio/fin, si hay dos
	valores iguales en posiciones[i][0] quedarán
	ordenados correlativamente los inicios antes de
	los finales
	*/
	mergeSort(posiciones, temp, 0, 2*N-1, 0);


	int intersecciones = 0;
	int acumulado = 0;
	int i = 0;
	int pivoteado = 0;
	int contador = 0;
	int inicios = 0;

	/*
	Para calcular el número de intersecciones, 
	se calcula cuántos puntos de inicios hay 
	entre el punto de inicio y el punto final 
	de cada disco, calculandolo en orden de
	aparición en el arreglo 'posiiones'. Estos 
	valores son sumados.
	*/
	int coo = N-1;
	int maximos_a_encontrar = N;
	while (inicios < coo && contador < 2*N){

		if (posiciones[contador][1] == 0){
			i = contador+1;
			acumulado = 0;
			inicios++;
			maximos_a_encontrar--;
			pivoteado = posiciones[contador][2];


			/*
			while desde el inicio de un círculo
			hasta llegar a su posición final.
			*/
			while (i < 2*N && (posiciones[i][2] != pivoteado &&
				maximos_a_encontrar > 0		)){
				if (posiciones[i][1] == 0){
					acumulado++;
				}
				i++;
			}

			intersecciones+= acumulado;
			if (intersecciones > 10000000){
				return -1;
			}
		}
		
		contador++;

	}

	return intersecciones;
}
int main(void)
{  
	int unsorted1[6] = {0, 1, 3, 2, 4, 0}; 
	int sorted[6] = {0, 0, 1, 2, 3, 4}; 
	int unsorted2[6] = {0, 20, 11, 11, 47, 32};
	int sorted1[6] = {0, 11, 11, 20, 32, 47};
	int unsorted3[6] = {0, 24, 1, 36, 5, 2};
	int sorted2[6] = {0, 1, 2, 5, 24, 36};
	int test_sorted1[6] = {0, 1, 2, 3, 4, 5};
	int test_unsorted2[6] = {0, 1, 2, 3, 4, 5};
	int sorted4[1] = {1};
	int unsorted4[1] = {1};
	int sorted5[6] = {0, 0, 0, 0, 0, 0};
	int unsorted5[6] = {0, 0, 0, 0, 0, 0};
	int sorted6[15] = {32, 12, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
	int unsorted6[15] = {32, 12, 3, 4, 8, 10, 14, 5, 9, 6, 11, 15, 13, 7, 12};
	
	//sorts the unsorted arrays
	mergeSort(unsorted1, 1, 5);
	mergeSort(unsorted2, 1, 5);
	mergeSort(unsorted3, 1, 5);
	mergeSort(test_sorted1, 1, 5);
	mergeSort(unsorted4, 1, 1);
	mergeSort(unsorted5, 1,5);
	mergeSort(unsorted6, 4, 14);
	
	//tests that repeating element array wont get messed up
	assert(sorted5[1] == unsorted5[1]);
	assert(sorted5[2] == unsorted5[2]);
	assert(sorted5[4] == unsorted5[4]);
	
	//test that the function does not mess up a one element array
	assert(sorted4[0] == unsorted4[0]);
	
	//tests that it does not mess up a sorted array
	assert(test_sorted1[1] == test_unsorted2[1]);
	assert(test_sorted1[4] == test_unsorted2[4]);
	assert(test_sorted1[2] == test_unsorted2[2]);
	
	//compares the same index of the sorted and unsorted array
	//they all should equal since the unsorted should be sorted now
	assert(sorted[1] == unsorted1[1]);
	assert(sorted[4] == unsorted1[4]);
	assert(sorted[2] == unsorted1[2]);
	
	assert(sorted1[1] == unsorted2[1]);
	assert(sorted1[4] == unsorted2[4]);
	assert(sorted1[2] == unsorted2[2]);
	
	assert(sorted2[1] == unsorted3[1]);
	assert(sorted2[3] == unsorted3[3]);
	assert(sorted2[2] == unsorted3[2]);
	
	//tests when only part of the array is sorted
	assert(sorted6[6] == unsorted6[6]);
	assert(sorted6[8] == unsorted6[8]);
	assert(sorted6[10] == unsorted6[10]);
	assert(sorted6[4] == unsorted6[4]);
	assert(sorted6[13] == unsorted6[13]);
	
	return 0;
}
예제 #19
0
파일: main.cpp 프로젝트: wesdizzle/Teaching
int main(int argc, char * argv[])
{
	clock_t time;
	std::vector<int> input;
	std::vector<int> output;

	//check for proper number of command-line arguments
	if(argc != 2)
	{
		std::cerr << "Incorrect number of arguments!" << std::endl;
		
		return 0;
	}

	//read values from input file and populate array
	std::ifstream file;
	std::string line;
	file.open(argv[1]);
	if(file.is_open())
	{
		while(getline(file, line))
		{
			input.push_back(atoi(line.c_str()));
		}
		file.close();
	}
	else
	{
		std::cerr << "Unable to open file!" << std::endl;

		return 0;
	}

	std::cout << "The vector has been populated." << std::endl;

	//perform insertion sort on the vector
	std::cout << "Insertion sort is beginning." << std::endl;
	time = clock();

	output = insertionSort(input);

	time = clock() - time;
	std::cout << "Insertion sort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	//perform selection sort on the vector
	std::cout << "Selection sort is beginning." << std::endl;
	time = clock();

	output = selectionSort(input);

	time = clock() - time;
	std::cout << "Selection sort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	//perform merge sort on the vector
	std::cout << "Merge sort is beginning." << std::endl;
	time = clock();

	output = mergeSort(input);

	time = clock() - time;
	std::cout << "Merge sort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	//perform heapsort on the vector
	std::cout << "Heapsort is beginning." << std::endl;
	time = clock();

	output = heapSort(input);

	time = clock() - time;
	std::cout << "Heapsort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	//perform quicksort on the vector
	std::cout << "Quicksort is beginning." << std::endl;
	time = clock();

	output = quickSort(input);

	time = clock() - time;
	std::cout << "Quicksort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	//perform bubble sort on the vector
	std::cout << "Bubble sort is beginning." << std::endl;
	time = clock();

	output = bubbleSort(input);

	time = clock() - time;
	std::cout << "Bubble sort finished in " << double(time) / CLOCKS_PER_SEC << " seconds." << std::endl;
	if(output.size() <= 10)print(output);

	return 0;
}
예제 #20
0
// 정해진 정렬을 수행하고 수행 시간을 리턴해주는 함수 
float do_sort(int sort_code, int* randomNum, int* bCheckExistOfNum,  int number){
	time_t startTime,endTime;	// 함수 수행 시작시간, 종료시간 
	int i; 
	float gap;					// 총 함수 수행시간 
	switch(sort_code){			// 정렬 코드에 따라서 다른 정렬을 수행한다 
		//삽입 정렬의 경우 
		case 1:
			printf("난수 %d개를 생성 중입니다...\n", number);
			Sleep(3000);
            generate_random_number(randomNum, bCheckExistOfNum, number);
            printf("\n난수가 %d개 생성되었습니다.\n", number);
            Sleep(3000);
            printf("정렬 알고리즘을 시작합니다..\n");
            startTime = clock();
			insertSort(randomNum, number);
			endTime = clock();
			printf("정렬 알고리즘이 완료되었습니다.\n");
			gap=(float)(endTime-startTime)/(CLOCKS_PER_SEC); //계산
			printf("총 수행 시간 : %f초\n", gap);
			Sleep(3000);
			printf("정렬된 결과를 출력합니다.\n");
			Sleep(3000);
			for(i = 0 ; i < number ; i++){
				printf("%d ", randomNum[i]);
			}
			printf("\n정렬이 완료되었습니다.\n");
			Sleep(3000); 
			return gap;
		// 선택 정렬의 경우 
		case 2:
			printf("난수 %d개를 생성 중입니다...\n", number);
			Sleep(3000);
            generate_random_number(randomNum, bCheckExistOfNum, number);
            printf("\n난수가 %d개 생성되었습니다.\n", number);
            Sleep(3000);
            printf("정렬 알고리즘을 시작합니다..\n");
            startTime = clock();
			selectionSort(randomNum, number);		// 선택 정렬 실행. 
			endTime = clock();
			printf("정렬 알고리즘이 완료되었습니다.\n");
			gap=(float)(endTime-startTime)/(CLOCKS_PER_SEC); //계산
			printf("총 수행 시간 : %f초\n", gap);
			Sleep(3000);
			printf("정렬된 결과를 출력합니다.\n");
			Sleep(3000);
			for(i = 0 ; i < number ; i++){
				printf("%d ", randomNum[i]);
			}
			printf("\n정렬이 완료되었습니다.\n");
			Sleep(3000); 
			return gap;
		// 합병 정렬의 경우	
		case 3:
			printf("난수 %d개를 생성 중입니다...\n", number);
			Sleep(3000);
            generate_random_number(randomNum, bCheckExistOfNum, number);
            printf("\n난수가 %d개 생성되었습니다.\n", number);
            Sleep(3000);
            printf("정렬 알고리즘을 시작합니다..\n");
            startTime = clock();
			mergeSort(randomNum, 0, number);			// 합병 정렬 실행. 
			endTime = clock();
			printf("정렬 알고리즘이 완료되었습니다.\n");
			gap=(float)(endTime-startTime)/(CLOCKS_PER_SEC); //계산
			printf("총 수행 시간 : %f초\n", gap);
			Sleep(3000);
			printf("정렬된 결과를 출력합니다.\n");
			Sleep(3000);
			for(i = 0 ; i < number ; i++){
				printf("%d ", randomNum[i]);
			}
			printf("\n정렬이 완료되었습니다.\n");
			Sleep(3000); 
			return gap;
		// 힙 정렬의 경우	
		case 4:
			printf("난수 %d개를 생성 중입니다...\n", number);
			Sleep(3000);
            generate_random_number(randomNum, bCheckExistOfNum, number);
            printf("\n난수가 %d개 생성되었습니다.\n", number);
            Sleep(3000);
            printf("정렬 알고리즘을 시작합니다..\n");
            startTime = clock();
			Heap_Sort(randomNum, number);			// 힙 정렬 실행. 
			endTime = clock();
			printf("정렬 알고리즘이 완료되었습니다.\n");
			gap=(float)(endTime-startTime)/(CLOCKS_PER_SEC); //계산
			printf("총 수행 시간 : %f초\n", gap);
			Sleep(3000);
			printf("정렬된 결과를 출력합니다.\n");
			Sleep(3000);
			for(i = 0 ; i < number ; i++){
				printf("%d ", randomNum[i]);
			}
			printf("\n정렬이 완료되었습니다.\n");
			Sleep(3000); 
			return gap;
	}
}
예제 #21
0
void MergeSort::sort(Data* data, int n, int (*compar)(Contact&, Contact&)) {
    int first = 0; //p is first index
    int last = n-1; //r is last index
    mergeSort(data, first, last, (*compar));
}
예제 #22
0
파일: main.cpp 프로젝트: StoneMa/coderepo
void merge_sort(int a[], int n)
{
    static int help[MAX];         //helper space used in merge sort
    mergeSort(help, a, 0, n-1, 1);//use help as temporary storage, store the ordered array to a
}